Может быть GROUP BY
с GROUPING SETS
поможет вам:
SELECT
--GROUPING_ID(country,province,city),
CASE GROUPING_ID(country,province,city)
WHEN 7 THEN 'total'
WHEN 3 THEN 'country total - '+country
WHEN 1 THEN 'province total - '+province
ELSE 'city - '+city
END row_title,
country,
province,
city,
COUNT(DISTINCT province) province_count,
COUNT(DISTINCT city) city_count,
SUM(people) people_count
FROM YourTable
GROUP BY GROUPING SETS(
(country,province,city),
(country,province),
(country),
()
)
ORDER BY country,province,city
Данные испытаний:
CREATE TABLE YourTable(country varchar(20),province varchar(20),city varchar(20),people int)
INSERT YourTable(country,province,city,people)VALUES
('country1','province1','city1',200),
('country1','province1','city2',150),
('country1','province2','city3',350),
('country2','province3','city4',75)
Также попробуйте использовать следующее:
SELECT column_name,value
FROM
(
SELECT
COUNT(DISTINCT province) [province count],
COUNT(DISTINCT city) [city count],
SUM(people) [people count]
FROM YourTable
) q UNPIVOT(value FOR column_name IN([province count],[city count],[people count])) u