欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

sql小计汇总 rollup用法实例分析

程序员文章站 2022-05-17 08:48:37
这里介绍sql server2005里面的一个使用实例: create table tb(province nvarchar(10),city nvarchar(10),s...
这里介绍sql server2005里面的一个使用实例:
create table tb(province nvarchar(10),city nvarchar(10),score int)
insert tb select '陕西','西安',3
union all select '陕西','安康',4
union all select '陕西','汉中',2
union all select '广东','广州',5
union all select '广东','珠海',2
union all select '广东','东莞',3
union all select '江苏','南京',6
union all select '江苏','苏州',1
go
1、 只有一个汇总
select province as 省,sum(score) as 分数 from tb group by province with rollup
结果:
广东 10
江苏 7
陕西 9
null 26

select case when grouping(province)=1 then '合计' else province end as 省,sum(score) as 分数 from tb group by province with rollup
结果:
广东 10
江苏 7
陕西 9
合计 26

2、两级,中间小计最后汇总
select province as 省,city as 市,sum(score) as 分数 from tb group by province,city with rollup
结果:
广东 东莞 3
广东 广州 5
广东 珠海 2
广东 null 10
江苏 南京 6
江苏 苏州 1
江苏 null 7
陕西 安康 4
陕西 汉中 2
陕西 西安 3
陕西 null 9
null null 26
select province as 省,city as 市,sum(score) as 分数,grouping(province) as g_p,grouping(city) as g_c from tb group by province,city with rollup

结果:
广东 东莞 3 0 0
广东 广州 5 0 0
广东 珠海 2 0 0
广东 null 10 0 1
江苏 南京 6 0 0
江苏 苏州 1 0 0
江苏 null 7 0 1
陕西 安康 4 0 0
陕西 汉中 2 0 0
陕西 西安 3 0 0
陕西 null 9 0 1
null null 26 1 1

select case when grouping(province)=1 then '合计' else province end 省,
case when grouping(city)=1 and grouping(province)=0 then '小计' else city end 市,
sum(score) as 分数
from tb group by province,city with rollup
结果:
广东 东莞 3
广东 广州 5
广东 珠海 2
广东 小计 10
江苏 南京 6
江苏 苏州 1
江苏 小计 7
陕西 安康 4
陕西 汉中 2
陕西 西安 3
陕西 小计 9
合计 null 26