按年、月、日分组集
Grouping sets by year, month, and date
是否可以使用 GROUPING SETS
汇总日期、月份和年份,其中显示日期并将其分组为月份和年份,并且显示月份和年份的值而不是 null
?
这是示例数据,以及我尝试使用分组集
create table #tbl_data
(
employeeId int
,productLine int
,salesDate datetime
,salesTotal money
)
insert into #tbl_data
values
(1,1,'02/09/2017',199)
,(1,1,'04/10/2017',379)
,(2,1,'04/21/2017',323)
,(2,1,'04/10/2017',461)
,(2,1,'06/11/2017',304)
,(3,1,'01/28/2017',147)
,(3,1,'02/09/2017',320)
,(4,1,'03/07/2017',344)
,(4,1,'03/13/2017',176)
select
productLine,
employeeId,
salesDate,
mon=month(salesdate),
yr=year(salesdate),
sum(salesTotal) as salesTotal
from
#tbl_data
group by grouping sets
(
(productLine, employeeId, salesDate)
,(productLine, employeeId)
,(productLine)
)
这是查询返回的内容(左)和我想要完成的内容(右)
您可以使用:
;WITH cte AS (
select
productLine,
employeeId,
salesDate,
mon=month(salesdate),
yr=year(salesdate),
salesTotal
from #tbl_data
)
select
productLine,
employeeId,
salesDate,
mon,
yr ,
sum(salesTotal) as salesTotal
from cte
group by grouping sets
(
(productLine, employeeId, salesDate, yr)
,(productLine, employeeId, yr)
,(productLine)
,(productLine, mon, yr)
);
是否可以使用 GROUPING SETS
汇总日期、月份和年份,其中显示日期并将其分组为月份和年份,并且显示月份和年份的值而不是 null
?
这是示例数据,以及我尝试使用分组集
create table #tbl_data
(
employeeId int
,productLine int
,salesDate datetime
,salesTotal money
)
insert into #tbl_data
values
(1,1,'02/09/2017',199)
,(1,1,'04/10/2017',379)
,(2,1,'04/21/2017',323)
,(2,1,'04/10/2017',461)
,(2,1,'06/11/2017',304)
,(3,1,'01/28/2017',147)
,(3,1,'02/09/2017',320)
,(4,1,'03/07/2017',344)
,(4,1,'03/13/2017',176)
select
productLine,
employeeId,
salesDate,
mon=month(salesdate),
yr=year(salesdate),
sum(salesTotal) as salesTotal
from
#tbl_data
group by grouping sets
(
(productLine, employeeId, salesDate)
,(productLine, employeeId)
,(productLine)
)
这是查询返回的内容(左)和我想要完成的内容(右)
您可以使用:
;WITH cte AS (
select
productLine,
employeeId,
salesDate,
mon=month(salesdate),
yr=year(salesdate),
salesTotal
from #tbl_data
)
select
productLine,
employeeId,
salesDate,
mon,
yr ,
sum(salesTotal) as salesTotal
from cte
group by grouping sets
(
(productLine, employeeId, salesDate, yr)
,(productLine, employeeId, yr)
,(productLine)
,(productLine, mon, yr)
);