使用HADING和GROUPING SETS

时间:2015-04-05 22:11:47

标签: sql sql-server

我的sql字符串如下

SELECT Country, City, COUNT(*) AS [Count]
FROM   CountriesAndCities
GROUP  BY GROUPING SETS ( ( Country, City ), ( Country) )     
ORDER  BY Country, City 

我的结果如下

Country     City        CountryCount
----------  ----------  ------------
France      NULL        4 
France      Paris       4           
Spain       NULL        6 
Spain       Barcelona   3           
Spain       Madrid      3   

如果国家/地区只有一个城市记录,我可以使用HAVING

获得如下结果
Country     City        CountryCount
----------  ----------  ------------
France      Paris       4           
Spain       NULL        6 
Spain       Barcelona   3           
Spain       Madrid      3  

1 个答案:

答案 0 :(得分:6)

SELECT Country, City, COUNT(*) AS [Count]
FROM   CountriesAndCities
GROUP  BY GROUPING SETS ( ( Country, City ), ( Country) )
HAVING GROUPING(City) = 0
    OR COUNT(DISTINCT City) > 1
ORDER  BY Country, City
  • GROUPING(City) = 0如果City当前按字段分组的字段之一。
  • 相反,当GROUPING(City) = 1然后City报告为NULL时。

这意味着我们始终包含提及City的行(不是NULL)。

对于GROUPING(City) = 1又称City IS NULL的其他行,如果已将多个City汇总到结果中,我们只会包含该行。