我需要将这两个SQL脚本合二为一:从AdventureWorks数据库中获取每个城市的客户数量和每个国家/地区的客户总数
我几乎已经完成了,问题是我需要制作一个单TABLE
,但遇到多个COUNT
的问题。
USE AdventureWorks2014
SELECT person.Address.City, Count (*) AS Total
FROM person.Address
INNER JOIN person.StateProvince
ON person.Address.StateProvinceID = person.StateProvince.StateProvinceID
GROUP BY person.Address.City
ORDER BY Total DESC
USE AdventureWorks2014
SELECT person.StateProvince.CountryRegionCode, Count (*) AS Total
FROM person.Address
INNER JOIN person.StateProvince
ON person.Address.StateProvinceID = person.StateProvince.StateProvinceID
GROUP BY person.StateProvince.CountryRegionCode
ORDER BY Total DESC
答案 0 :(得分:0)
最简单的方法是GROUPING SETS
。但是,您可以使用SELECT COALESCE(a.City, sp.CountryRegionCode) as City_or_Region,
Count(*) AS Total
FROM person.Address a INNER JOIN
person.StateProvince sp
ON a.StateProvinceID = sp.StateProvinceID
GROUP BY GROUPING SETS ((a.City), (sp.CountryRegionCode))
ORDER BY Total DESC;
:
City
请注意,这会对数据做出一些假设:
NULL
永远不会City
。CountryRegionCode
和{{1}}永远不会有相同的值(如果需要,您可以将它们拆分为不同的列)。