2015-04-05 82 views
1

我的SQL字符串如下使用與GROUPING HAVING SETS

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 

回答

5
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 if City當前正在分組的字段之一。
  • 相反,當GROUPING(City) = 1City報告爲NULL

這意味着我們總是包含提到City的行(不是NULL)。

對於其他行,其中GROUPING(City) = 1又名City IS NULL,那麼如果多於一個City已彙總到結果中,那麼我們只包含該行。

+0

非常感謝你,但是使用這個查詢只返回NULL值的COUNTRY行 – Kerberos 2015-04-05 22:37:27

+1

對不起,我弄錯了;)我已經更新了它。請參閱https://msdn.microsoft.com/en-us/library/ms178544.aspx – MatBailie 2015-04-05 22:38:32