2014-10-17 95 views
0

所以我有一張有三個重要欄目的表格:商店位置,客戶和購買數量。例如:計算每個值在PostgreSQL表中出現的次數?

Store | Customer | Number of purchases 
A   Larry   2 
B   Moe   4 
C   Curly   7 
B   Tina   1 
A   Dina   6 
C   Archer   12 
D   Mallory  3 

我想要做的是獲得每次購買次數。也就是說,統計顧客進行1次購買,2次購買,3次購買,4次購買等的次數,類似直方圖,按店鋪分組。

Store | 1 Purchase | 2 Purchases | 3 Purchases... 
A   1    3     2 
B   2    1     4 
C   1    6     8 
D   4    4     2 

有沒有什麼聰明的辦法做到這一點,而無需手動發現什麼購買的最大數量是和創建一個分支數來計算的每一個?所以,我已經有

SELECT Store, 
     Count(CASE number_of_purchases when 1 then 1 else null end) as 1_purchase, 
     Count(CASE number_of_purchases when 2 then 1 else null end) as 2_purchase, 
     Count(CASE number_of_purchases when 3 then 1 else null end) as 3_purchase... 
FROM table 
GROUP BY Store; 

但是,因爲最大數量會隨時間改變,我想查詢自動計算,並考慮到這一點。任何幫助,將不勝感激!

+0

修復,謝謝你的提示。 – user2900369 2014-10-17 19:18:53

+2

您正在查找的是「數據透視表」或「交叉表」查詢。查看'tablefunc'擴展中的'crosstab'函數:http://www.postgresql.org/docs/current/static/tablefunc.html – 2014-10-17 19:21:35

回答

1

爲了得到正確的數據,你需要的只是group by和一個聚合函數。

select store, number_of_purchases, count(number_of_purchases) 
from Table1 
group by store, number_of_purchases 
order by store, number_of_purchases; 

對於格式,您需要使用tablefunc擴展中的一個crosstab()函數。沿着這些線路的東西。

select * 
from crosstab('select store, number_of_purchases, count(number_of_purchases) 
       from Table1 
       group by store, number_of_purchases 
       order by 1, 2', 
       'select n from generate_series(1, 12) n order by 1') 
    as (store text, "1" int, "2" int, "3" int, "4" int, 
        "5" int, "6" int, "7" int, "8" int, 
        "9" int, "10" int, "11" int, "12" int) 
; 

就我個人而言,我不喜歡這種數據的交叉表。您可能會得到數百或數千列寬的輸出,大部分「單元」都是空的。

0

試試這個:

SELECT 
    Store, number_of_purchases, COUNT(DISTINCT number_of_purchases) AS cnt 
FROM table 
GROUP BY Store, number_of_purchases 

結果將排列成行(而不是在列),因爲你不知道什麼是購買的每個商店的最大數量。

由於它們將按Store和number_of_purchases進行排序,因此很容易對結果進行循環。

相關問題