码迷,mamicode.com
首页 > 数据库 > 详细

Oracle分组函数之ROLLUP

时间:2015-06-25 17:18:45      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:

功能介绍:

首先是进行无字段的聚合,然后在对字段进行从左到右依次组合后聚合

 

创建表:

技术分享
1 Create Table score
2 (
3   classID Int,
4   studentName Varchar2(50),
5   subject varchar2(50),
6   score Int
7 );
View Code

 

插入测试数据:

技术分享
 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);
View Code

 

普通分组函数,统计每个班级的总分:

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

 

Oracle分组函数之ROLLUP

标签:

原文地址:http://www.cnblogs.com/yuan-yuan/p/4600194.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!