日期:2014-05-16  浏览次数:20377 次

Oracle group by 用法实例详解
Group by的语法

Select [filed1,fild2,]聚合函数(filed),

[Grouping(filed),]

[Grouping_id(filed1,filed2,…)]

From tablename

Where condition

[Group by {rollup|cube}(filed,filed2)]

[having condition]

[order by filed1]

一、基本用法:

(1)我们通过几个例子来研究groupby的基本用法

创建测试表

SQL> create table sales(

2 empid number, --雇员ID

3 depid number, - -部门ID

4 area varchar(20), --区域

5 salenum number); --销售额


表已创建。


SQL> insert into sales values(1,1,'china',10);

SQL> insert into sales values(2,1,'china',10);

SQL> insert into sales values(3,1,'china',10);

SQL> insert into sales values(3,1,'china',10);

SQL> insert into sales values(3,1,'china',10);

SQL> insert into sales values(1,1,'china',10);

SQL> insert into sales values(2,1,'china',10);

SQL> insert into sales values(4,2,'china',10);

SQL> insert into sales values(4,2,'china',10);

SQL> insert into sales values(5,3,'us',10);

SQL> insert into sales values(5,3,'us',10);

需求1,按部门统计销售额 (简单用法)

SQL> select depid,sum(salenum) from sales group by depid;

DEPID SUM(SALENUM)

---------- ------------

1        70

2        20

3        20

需求2,按部门统计销售额,并且只显示销售总额小于30的部门及销售额(使用having子句)

SQL> select depid,sum(salenum) totalnum from sales

group by depid

having sum(salenum) <30;

DEPID SUM(SALENUM)

---------- ------------

2        20

3        20

注解:需求2需要使用having字名,而且在子句中不能使用别名,必须使用在select语句中书写的形式

(2)Where 和having的区别

Wheret和having子句都用来筛选数据,但是where是针对原数据进行筛选,而having子句只是针对汇总后的结果进行筛选,所以在需求二的例子中,想要对销售总额进行过滤只能使用having子句

(3)使用order by 排序

SQL> select depid,sum(salenum) from sales group by depid;

DEPID SUM(SALENUM)

---------- ------------

1       70

2       20

3       20

注意观察需求1的例子,depid是已经按照在depid升序排列的,这是因为oracle在做聚合统计的时候会首先对字段进行排序,所以最终的结果是按照升序进行排列的,如果order by后跟着多个字段,默认排序是先对第一个字段升序排序,然后再排第二个字段,以此类推,所以如果在应用中仅仅需要长序排序可以不用加order by 参数,毕竟这会影响性能

二、扩展用法:

扩展用法使用下面的表进行实验研究

SQL> create table testgroup(

2 a varchar(5),

3 b varchar(5),

4 c varchar(5),

5 n number);

建完测试表,然后插入两条测试数据

SQL> insert into testgroup values('a1','b1','c1',10);

SQL> insert into testgroup values('a1','b1','c1',20);

我们使用基本的group by 可以得到以下结果

SQL> select a,b,c,sum(n) total from testgroup group by a,b,c;

A        B      C     TOTAL

----- ----- ----- ----------

a1      b1     c1     30

(1)使用rollup操作符

Rollup意思有”卷起,汇总”的意思,他可以在使得在其括号中的字段,按从右到左的顺序分别group后显示,类似我们用多个group by 语句,然后union all起来,我们把针对上面的测试表,使用rollup操作符,看看效果

SQL> select a,b,c,sum(n) total from testgroup group by rollup(a,b,c);

Result:

A B C TOTAL
a1 b1 c1 30
a1 b1 30
a1 30
30
从上面结果可以看出, 除了对(a1,b1,c1)进行了汇总外,又从右向左分别对子句中的”a,b,c”字段进行了汇总,例如(a1,b1),(a1) ()

(2)使用cube操作符

Cube意思是立方,使用该操作符可以对操作符内的字段,进行遍历组合汇总,例如cube(a,b,c),那么就会产生8种组合结果,分别如下”a-b-c”,”a-b”,”a”,”a-c”,” b-c”,”b”,”c”,”空”,看下面的例子