日期:2014-05-18 浏览次数:20858 次
declare @tb table (id varchar(10),name varchar(1),dt datetime,num int) insert into @tb select '01','a','2008-01-01',1 insert into @tb select '01','a','2008-01-01',2 insert into @tb select '01','a','2008-01-02',3 insert into @tb select '01','a','2008-01-02',4 insert into @tb select '02','b','2008-01-01',5 insert into @tb select '02','b','2008-01-01',6 insert into @tb select '02','b','2008-01-02',7 insert into @tb select '02','b','2008-01-02',8 select id,name,dt,sum(num) as num from @tb group by id,name ,dt with rollup having grouping(id)+grouping(name)+grouping(dt)!=1
------解决方案--------------------
declare @tb table (id varchar(10),name varchar(1),dt datetime,num int)
insert into @tb select '01','a','2008-01-01',1
insert into @tb select '01','a','2008-01-01',2
insert into @tb select '01','a','2008-01-02',3
insert into @tb select '01','a','2008-01-02',4
insert into @tb select '02','b','2008-01-01',5
insert into @tb select '02','b','2008-01-01',6
insert into @tb select '02','b','2008-01-02',7
insert into @tb select '02','b','2008-01-02',8
select
case when grouping(id)=1 then '合计' else id end as id,
case when grouping(id)+grouping(name)=1 then '小计' else name end as name,
dt,
sum(num) as num from @tb
group by id,name ,dt
with rollup
having grouping(id)+grouping(name)+grouping(dt)!=1
id name dt num
01 a 2008-01-01 00:00:00.000 3
01 a 2008-01-02 00:00:00.000 7
01 小计 NULL 10
02 b 2008-01-01 00:00:00.000 11
02 b 2008-01-02 00:00:00.000 15
02 小计 NULL 26
合计 NULL NULL 36