I need these two SQL Scripts into one: to get amount of customer per city and the total of customer per country from AdventureWorks database
I almost have it done, the problem is that I need to make one single TABLE
, having problems with Multiple COUNT
's.
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
The simplest way is a UNION ALL
. However, you can do essentially the same thing with 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;
Note that this makes a couple of assumptions about the data:
City
is never NULL
.City
and CountryRegionCode
never have the same values (you can split these into separate columns if needed).