繁体   English   中英

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

[英]How do I do a nested group by query in 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中完成,任何帮助将不胜感激!

您可以将grouping sets用于聚合。 获得正确的顺序有些棘手:

select coalesce(country, continent), count(*) as Total
from places
group by grouping sets ( (country), (continent), () )
order by (grouping(country) + grouping(continent)) desc, min(continent), grouping(continent);

是db <>小提琴。

使用分组集

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM