Oracle分组函数之ROLLUP
功能介绍:
首先是进行无字段的聚合,然后在对字段进行从左到右依次组合后聚合
创建表:
1 Create Table score 2 ( 3 classID Int, 4 studentName Varchar2(50), 5 subject varchar2(50), 6 score Int 7 );
插入测试数据:
1 Insert Into score values (001,'小徐','语文',87); 2 Insert Into score values (001,'小徐','数学',98); 3 Insert Into score values (001,'小徐','外语',99); 4 Insert Into score values (002,'小吴','语文',80); 5 Insert Into score values (002,'小吴','数学',74); 6 Insert Into score values (002,'小吴','外语',65); 7 Insert Into score values (003,'小张','语文',89); 8 Insert Into score values (003,'小张','数学',78); 9 Insert Into score values (003,'小张','外语',84); 10 Insert Into score values (004,'小孙','语文',100); 11 Insert Into score values (004,'小孙','数学',100); 12 Insert Into score values (004,'小孙','外语',100); 13 Insert Into score values (001,'小彭','语文',87); 14 Insert Into score values (001,'小彭','数学',99); 15 Insert Into score values (001,'小彭','外语',65); 16 Insert Into score values (004,'小叶','语文',100); 17 Insert Into score values (004,'小叶','数学',100); 18 Insert Into score values (004,'小叶','外语',100); 19 Insert Into score values (003,'小刘','语文',79); 20 Insert Into score values (003,'小刘','数学',90); 21 Insert Into score values (003,'小刘','外语',65); 22 Insert Into score values (002,'小童','语文',96); 23 Insert Into score values (002,'小童','数学',93); 24 Insert Into score values (002,'小童','外语',97);
普通分组函数,统计每个班级的总分:
Select t.Classid, Sum(t.Score) From Score t Group By t.Classid;
查询结果:
加上Rollup,统计每个班级的总分和所有班级的总分:
Select t.Classid, Sum(t.Score) From Score t Group By Rollup(t.Classid);
查询结果:
先进行无字段的聚合(1),再对Classid聚合(3),相当于:
1 Select Null, Sum(t.Score) From Score t 2 Union All 3 Select t.Classid, Sum(t.Score) From Score t Group By t.Classid;
在看看两个字段的,统计每个班级的总分、所有班级的总分和每个学生的总成绩:
Select t.classid,t.studentname,Sum(t.score) From Score t Group By Rollup(t.classid,t.studentname);
查询结果:
先进行无字段的聚合(1),再对Classid聚合(3),在对Classid和Studentname组合聚合,相当于:
1 Select Null, Null, Sum(t.Score) From Score t 2 Union All 3 Select t.Classid, Null, Sum(t.Score) From Score t Group By t.Classid 4 Union All 5 Select t.Classid, t.Studentname, Sum(t.Score) From Score t Group By t.Classid, t.Studentname