我需要计算每个城市,州和国家的计数。例如,如果我在表T1中有以下数据:
NetworkOnMainThread
查询应该导致:
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
如果我分组并计数,那么我需要编写3个不同的查询。但我想在一个查询中做到这一点。请帮忙。
答案 0 :(得分: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。