oracle中的資料統計
一、使用ROLLUP和CUBE彙總統計
1、測試資料
create table A
(
GRADE CHAR(5),
ID CHAR(5),
NUM CHAR(5)
)
insert into a values('a',1,1);
insert into a values('a',2,2);
insert into a values('b',2,4);
insert into a values('b',3,4);
2、檢視幾個分組結果
SQL> select sum(num) from a; //全部求和
SUM(NUM)
----------
11
SQL> select grade,sum(num) from a group by grade;//按grade分組
GRADE SUM(NUM)
----- ----------
a 3
b 8
SQL> select id,sum(num) from a group by id;;//按id分組
ID SUM(NUM)
----- ----------
1 1
2 6
3 4
SQL> select id,grade,sum(num) from a group by grade,id;;//按grade,id分組
ID GRADE SUM(NUM)
----- ----- ----------
1 a 1
2 a 2
2 b 4
3 b 4
3、使用rollup分組結果
SQL> select grade,id,sum(num) from a group by rollup(id,grade);
GRADE ID SUM(NUM)
----- ----- ----------
a 1 1
1 1
a 2 2
b 2 4
2 6
b 3 4
3 4
11
8 rows selected
SQL> select id,grade,sum(num) from a group by rollup(id,grade);
ID GRADE SUM(NUM)
----- ----- ----------
1 a 1
1 1
2 a 2
2 b 4
2 6
3 b 4
3 4
11
可以看出調換id和grade位置結果是不一樣的,當使用rollup分組時,首先是按第一個引數分組,然後第一個,第二個引數分組 ,如果跟多的話依次類推
4、使用cube分組
SQL> select id,grade,sum(num) from a group by cube(id,grade);
ID GRADE SUM(NUM)
----- ----- ----------
11
a 3
b 8
1 1
1 a 1
2 6
2 a 2
2 b 4
3 4
3 b 4
10 rows selected
SQL> select grade,id,sum(num) from a group by cube(grade,id);
GRADE ID SUM(NUM)
----- ----- ----------
11
1 1
2 6
3 4
a 3
a 1 1
a 2 2
b 8
b 2 4
b 3 4
使用cube分組時調換引數的位置並不會影響結果,因為cube會為每個引數單獨分組統計,然後按照然後第一個,第二個引數分組 ,第二個參,第三個引數一次分組統計
5、多個引數實驗
(1)修改表
alter table a add grade1 char(5);
SQL> select * from a;
GRADE ID NUM GRADE1
----- ----- ----- ------
a 1 1 a1
a 2 2 a1
b 2 4 b1
b 3 4 b2
(2)使用rollup
SQL> select grade,grade1,id,sum(num) from a group by rollup(grade,grade1,id);
GRADE GRADE ID SUM(NUM)
----- ----- ----- ----------
a a1 1 1
a a1 2 2 按grade,grade1和id分組
a a1 3 按grade和grade1分組
a 3 按grade分組
b b1 2 4
b b1 4
b b2 3 4
b b2 4
b 8
11
(2)使用cube
SQL> select grade,grade1,id,sum(num) from a group by cube(grade,grade1,id);
GRADE GRADE ID SUM(NUM)
----- ----- ----- ----------
11
1 1
2 6 按id分組
3 4
a1 3 按grade1分組
a1 1 1 按grade1和id分組
a1 2 2
b1 4
b1 2 4
b2 4
b2 3 4
a 3 按grade分組
a 1 1
a 2 2
a a1 3 按grade和grade1分組
a a1 1 1 按grade,id和grade1分組
a a1 2 2
b 8
b 2 4 按grade,id分組
b 3 4
b b1 4
b b1 2 4
b b2 4
b b2 3 4
24 rows selected.
其實cube和rollup的區別就是cube採用排列組和,所有的引數排列組合,兒而rollup只是依次組合