--建立测试环境
create table #tb(日期 varchar(10),组织结构 varchar(10),发送数量 int)
insert #tb(日期,组织结构,发送数量)
select '2007-07','技术部门','1' union all
select '2007-07','总经理','1' union all
select '2007-08','总经理','2' union all
select '2007-10','技术部门','1'
go
--执行测试语句
select case when grouping(日期)= 0 then t.日期 else '合计' end as 日期
,case when grouping(组织结构) = 0 then t.组织结构
when grouping(组织结构) = 1 and grouping(日期) = 1 then '' else '小结' end as 组织结构
,sum(t.发送数量 ) as 发送数量
from #tb t
group by 日期,组织结构 with rollup
go
--删除测试环境
drop table #tb
go
/*--测试结果
日期 组织结构 发送数量
---------- ---------- -----------
2007-07 技术部门 1
2007-07 总经理 1
2007-07 小结 2
2007-08 总经理 2
2007-08 小结 2
2007-10 技术部门 1
2007-10 小结 1
合计 5
declare @t table(日期 varchar(10),组织结构 varchar(10),发送数量 int)
insert into @t select '2007-07','技术部门',1
insert into @t select '2007-07','总经理 ',1
insert into @t select '2007-08','总经理 ',2
insert into @t select '2007-10','技术部门',1
select
(case when 日期 is null then '合计' when 组织结构 is null then '' else 日期 end) as 日期,
(case when 日期 is not null and 组织结构 is null then '小计' else 组织结构 end) as 组织结构,
sum(发送数量) as 发送数量
from
@t t
group by
日期,组织结构
with rollup
select isnull(日期,case when 组织结构 is null then '合计' else '' end),isnull(组织结构,case when 日期 is null then '' else '小结' end),sum(发送数量) from 表 group by 日期,组织结构 with rollup