标签:
转自:http://www.cnblogs.com/dyufei/archive/2009/11/12/2573974.html
不言自明,看SQL就完全理解了,不需要过多解释,不错,分享之:
ROLLUP 运算符生成的结果集类似于 CUBE 运算符生成的结果集。
下面是 CUBE 和 ROLLUP 之间的具体区别:
创建表:
CREATE TABLE DEPART
(部门 char(10),员工 char(6),工资 int)
INSERT INTO DEPART SELECT ‘A‘,‘ZHANG‘,100
INSERT INTO DEPART SELECT ‘A‘,‘LI‘,200
INSERT INTO DEPART SELECT ‘A‘,‘WANG‘,300
INSERT INTO DEPART SELECT ‘A‘,‘ZHAO‘,400
INSERT INTO DEPART SELECT ‘A‘,‘DUAN‘,500
INSERT INTO DEPART SELECT ‘B‘,‘DUAN‘,600
INSERT INTO DEPART SELECT ‘B‘,‘DUAN‘,700
部门 员工 工资
A ZHANG 100
A LI 200
A WANG 300
A ZHAO 400
A DUAN 500
B DUAN 600
B DUAN 700
(1)GROUP BY
SELECT 部门,员工,SUM(工资)AS TOTAL
FROM DEPART
GROUP BY 部门,员工
结果:
A DUAN 500
B DUAN 1300
A LI 200
A WANG 300
A ZHANG 100
A ZHAO 400
(2)ROLLUP
SELECT 部门,员工,SUM(工资)AS TOTAL
FROM DEPART
GROUP BY 部门,员工 WITH ROLLUP
结果如下:
A DUAN 500
A LI 200
A WANG 300
A ZHANG 100
A ZHAO 400
A NULL 1500
B DUAN 1300
B NULL 1300
NULL NULL 2800
ROLLUP结果集中多了三条汇总信息:即部门A的合计,部门B的合计以及总合计。其中将部门B中的DUAN合计。
SELECT 部门,员工,SUM(工资)AS TOTAL
FROM DEPART
GROUP BY 部门,员工
union
SELECT 部门,‘NULL‘,SUM(工资)AS TOTAL
FROM DEPART
GROUP BY 部门
union
SELECT ‘NULL‘,‘NULL‘,SUM(工资)AS TOTAL
FROM DEPART
结果:
A DUAN 500
A LI 200
A NULL 1500
A WANG 300
A ZHANG 100
A ZHAO 400
B DUAN 1300
B NULL 1300
NULL NULL 2800
(3)CUBE
SELECT 部门,员工,SUM(工资)AS TOTAL
FROM DEPART
GROUP BY 部门,员工 WITH CUBE
结果:
A DUAN 500
A LI 200
A WANG 300
A ZHANG 100
A ZHAO 400
A NULL 1500
B DUAN 1300
B NULL 1300
NULL NULL 2800
NULL DUAN 1800
NULL LI 200
NULL WANG 300
NULL ZHANG 100
NULL ZHAO 400
CUBE的结果集是在 ROLLUP结果集的基础上多了5行,这5行相当于在ROLLUP结果集上在union 上以员工 (即CUBE)为 GROUP BY的结果。
SELECT 部门,员工,SUM(工资)AS TOTAL
FROM DEPART
GROUP BY 部门,员工 WITH CUBE
SELECT 部门,员工,SUM(工资)AS TOTAL
FROM DEPART
GROUP BY 部门,员工 WITH ROLLUP
union
SELECT ‘NULL‘,员工,SUM(工资)AS TOTAL
FROM DEPART
GROUP BY 员工
结果:
NULL NULL 2800
A NULL 1500
A DUAN 500
A LI 200
A WANG 300
A ZHANG 100
A ZHAO 400
B NULL 1300
B DUAN 1300
NULL DUAN 1800
NULL LI 200
NULL WANG 300
NULL ZHANG 100
NULL ZHAO 400
不用讲了吧,一对比结果就全明白了。
SQL 中GROUP BY 、ROLLUP、CUBE 关系和区别
标签:
原文地址:http://www.cnblogs.com/chengyeliang/p/4500931.html