簡體   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