我的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
答案 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
汇总到结果中,我们只会包含该行。