一、说明
数据库:SQL SERVER
使用场合:对group by 聚合之后的数据再进行合计
二、数据准备
CREATE TABLE test.cnblogs.win_func (fname VARCHAR(200),fcity VARCHAR(200),fage INT,fsalary INT) ; INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Tom','BeiJing',20,3000); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Tim','ChengDu',21,4000); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Jim','BeiJing',22,3500); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Lily','London',21,2000); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('John','NewYork',22,1000); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('YaoMing','BeiJing',20,3000); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Swing','London',22,2000); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Guo','NewYork',20,2800); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('YuQian','BeiJing',24,8000); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Ketty','London',25,8500); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Kitty','ChengDu',25,3000); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Merry','BeiJing',23,3500); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Smith','ChengDu',30,3000); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Bill','BeiJing',25,2000); INSERT INTO test.cnblogs.win_func(FName,FCity,FAge,FSalary) VALUES('Jerry','NewYork',24,3300);
三、关键字
3.1 GROUPING
该函数再其参数列的值为超级分组记录所产生的的NULL时返回1,其他返回0。
SELECT grouping(fcity) as fcity,grouping(fage) as fage,sum(fsalary) as '薪水' FROM test.cnblogs.win_func group by fcity,fage
本例为极端情况,没有超级分组,也不会有超级分组记录所产生的NULL;
一般与case when 配合使用,后面将和其他关键字配合说明
3.2 ROLLUP
同时得到小计与合计,类似Excel透视表
SELECT fcity,fage,sum(fsalary) as '薪水' FROM test.cnblogs.win_func group by ROLLUP(fcity,fage)
与GROUPING配合使用
SELECT grouping(fcity) as fcity,grouping(fage) as fage,sum(fsalary) as '薪水' FROM test.cnblogs.win_func group by ROLLUP(fcity,fage)
原超级分组记录所产生的的NULL时返回1,其他返回0。
与GROUPING、CASE WHEN 配合使用
select case when GROUPING(fcity)=1 then '总计' else fcity end as fcity, fage,sum(fsalary) as "薪水" FROM test.cnblogs.win_func group by ROLLUP(fcity,fage)
3.3 CUBE
相较于ROLLUP,有更多的小计
SELECT fcity,fage,sum(fsalary) as '薪水' FROM test.cnblogs.win_func group by cube(fage,fcity) --注意字段书写顺序
3.3 GROUPING SETS
只统计CUB中的小计,不含总计
SELECT fage,fcity,sum(fsalary) as '薪水' FROM test.cnblogs.win_func group by grouping sets(fage,fcity)