如何为多个分组编写一个查询?

时间:2012-08-09 23:43:13

标签: tsql group-by

在下面的查询中,我如何只提出一个能给我结果的查询,而不是使用差异分组制作副本并将它们合并?

如果可能的话。

提前致谢!!

`create table #temp1 (col1 varchar(50), col2 varchar(50), col3 varchar(50), col4 varchar(50), col5 varchar(50), sumit int)

insert into #temp1 values('AEAMS','CE Europe', 'Belarus', 'Govt', 'Int Fed Gvt', 1)
insert into #temp1 values('AEAMS','CE Europe', 'Belarus', 'Govt', 'Public Lib', 1)
insert into #temp1 values('AEDS','Japan', 'Japan C', 'Acad', 'CollUnive', 1)
insert into #temp1 values('AEDS','Japan', 'Japan F', 'Acad', 'Med', 1)
insert into #temp1 values('A- Regular Databases','UK and Ireland', 'Ireland', 'School', 'HIGH SCHOOL', 1)


Select col1 CC, null GM, null Terr, null Mkt, null Seg,  sum(sumit) SS
from #temp1
group by col1

Union

Select col1 CC, col2 GM, null Terr, null Mkt, null Seg,  sum(sumit) SS
from #temp1
group by col1, col2

Union

Select col1 CC, col2 GM, col3 Terr, null Mkt, null Seg,  sum(sumit) SS
from #temp1
group by col1, col2, col3

Union

Select col1 CC, col2 GM, col3 Terr, col4 Mkt, null Seg,  sum(sumit) SS
from #temp1
group by col1, col2, col3, col4, col5

1 个答案:

答案 0 :(得分:4)

尝试使用WITH ROLLUP

Select col1 CC, col2 GM, col3 Terr, col4 Mkt, null Seg,  sum(sumit) SS
from #temp1
group by col1, col2, col3, col4, col5
with rollup

SQL Fiddle Example