如何在SQL Server中按查询嵌套组?

时间:2019-07-15 19:02:07

标签: sql sql-server

我正在处理以下查询,该查询涉及产生一个涉及记录的嵌套结果的查询,但是我不确定如何进行子查询组,或者甚至根本不可能。

create table places (
id int not null identity primary key,
country varchar(32) not null,
continent varchar(32) not null,
hits int not null
);

insert into places (country, continent, hits) values 
('Canada', 'North America', 8),
('Canada', 'North America', 5),
('United States', 'North America', 2),
('Germany', 'Europe', 5),
('Germany', 'Europe', 9),
('Germany', 'Europe', 1),
('France', 'Europe', 3),
('Italy', 'Europe', 6),
('Italy', 'Europe', 9),
('China', 'Asia', 7),
('China', 'Asia', 8),
('Japan', 'Asia', 7);

select country, count(*) as Total from places
group by country with rollup
order by country asc;

此查询产生以下结果:

(null)                12
Canada                2
China                 2
France                1
Germany               3
Italy                 2
Japan                 1
United States         1

我希望查询产生如下所示的结果:

(null)                12
Asia                  3
  China               2
  Japan               1
Europe                6
  France              1
  Germany             3
  Italy               2
North America         3
  Canada              2
  United States       1

这是一个SQL Fiddle链接,可用于此:http://sqlfiddle.com/#!18/9145b/2

希望这可以在SQL Server中完成,任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:4)

您可以使用!进行汇总。获得正确的顺序有些棘手:

grouping sets

Here是db <>小提琴。

答案 1 :(得分:0)

使用分组集

select coalesce ('  ' + country, continent, 'TOTAL') item,  count(*) as Total 
from places
group by GROUPING sets((country, continent), (continent), ()) 
order by coalesce(continent, 'Z'), country asc;