sql 中的grouping函数
代码
declare @Temp table(Code varchar(10), ID int, SInt int)
insert into @Temp(Code, ID, SInt)
select '01',1,3
union
select '01',2,3
union
select '01',2,3
union
select '02',1,3
union
select '02',3,5
union
select '02',2,6
union
select '03',3,5
union
select '03',1,6
select case when grouping(code)=1 then 'Grand Total:'
when grouping(ID)=1 then Code+' Total:'
else Code
end as LevelCode, ID, SUM(Sint) as S
from @Temp
group by Code, ID
with rollup
insert into @Temp(Code, ID, SInt)
select '01',1,3
union
select '01',2,3
union
select '01',2,3
union
select '02',1,3
union
select '02',3,5
union
select '02',2,6
union
select '03',3,5
union
select '03',1,6
select case when grouping(code)=1 then 'Grand Total:'
when grouping(ID)=1 then Code+' Total:'
else Code
end as LevelCode, ID, SUM(Sint) as S
from @Temp
group by Code, ID
with rollup
这里面的
case when grouping(code)=1 then 'Grand Total:'
when grouping(ID)=1 then Code+' Total:'
else Code
end as LevelCode
when的顺序是按照group by 里面的字段顺序。when grouping(ID)=1 then Code+' Total:'
else Code
end as LevelCode
继续追寻。。。。。。