2015-12-16 25 views
3

我需要計算每個城市,州和國家的計數。例如,如果我在我的表T1以下數據:Postgresql在一個查詢中計算不同的組

name  city state country 
------------------------------ 
name1  c1  s1  C1 
name2  c1  s1  C1 
name3  c2  s1  C1 
name4  c3  s1  C1 
name5  c4  s2  C1 
name6  c5  s2  C1 
name7  c5  s3  C1 
name8  c12 s12  C2 

查詢應結果:

city state country citycount, statecount, countrycount 
------------------------------------------------------------------- 
c1  s1  C1  2   4    7 
c2  s1  C1  1   4    7 
c3  s1  C1  1   4    7 
c4  s2  C1  1   2    7 
c5  s2  C1  1   2    7 
c5  s3  C1  1   1    7 
c12  s12  C2  1   1    1 

,如果我通過做組再算上我需要寫3次不同的查詢。但我想在一個查詢中完成。請幫忙。

回答

2

您可以使用window functions,例如,一個解決方案可能是這一個:

SELECT DISTINCT city 
    ,STATE 
    ,country 
    ,count(*) OVER (PARTITION BY city,STATE,country) AS citycount 
    ,count(*) OVER (PARTITION BY STATE,country) AS statecount 
    ,count(*) OVER (PARTITION BY country) AS countrycount 
FROM T1 
ORDER BY city 
    ,STATE 
    ,country 

請參閱小提琴here

相關問題