GROUPING
功能描述
GROUPING函数用于区分分组后的普通行和聚合行。如果是聚合行,则返回1,反之,则是0。
注意事项
该函数仅适用于select语句并包含GROUP BY的情况。
语法格式
GROUPING( col_expr )
参数说明
col_expr
列名。
示例
1、创建测试表并插入数据。
create table group_test (group_id int, job varchar2(10), name varchar2(10), salary int);
insert into group_test values (10,'Coding', 'Bruce',1000);
insert into group_test values (10,'Programmer','Clair',1000);
insert into group_test values (10,'Architect', 'Gideon',1000);
insert into group_test values (10,'Director', 'Hill',1000);
insert into group_test values (20,'Coding', 'Jason',2000);
insert into group_test values (20,'Programmer','Joey',2000);
insert into group_test values (20,'Architect', 'Martin',2000);
insert into group_test values (20,'Director', 'Michael',2000);
insert into group_test values (30,'Coding', 'Rebecca',3000);
insert into group_test values (30,'Programmer','Rex',3000);
insert into group_test values (30,'Architect', 'Richard',3000);
insert into group_test values (30,'Director', 'Sabrina',3000);
insert into group_test values (40,'Coding', 'Samuel',4000);
insert into group_test values (40,'Programmer','Susy',4000);
insert into group_test values (40,'Architect', 'Tina',4000);
insert into group_test values (40,'Director', 'Wendy',4000);
2、使用grouping函数:传入两个expr参数,使用GROUP BY ROLLUP生成分组集。
select group_id,job,grouping(group_id),grouping(job),grouping(group_id,job),sum(salary) from group_test group by rollup(group_id, job);
返回结果为:
group_id | job | grouping | grouping | grouping | sum
----------+------------+----------+----------+----------+-------
10 | Architect | 0 | 0 | 0 | 1000
10 | Coding | 0 | 0 | 0 | 1000
10 | Director | 0 | 0 | 0 | 1000
10 | Programmer | 0 | 0 | 0 | 1000
10 | | 0 | 1 | 1 | 4000
20 | Architect | 0 | 0 | 0 | 2000
20 | Coding | 0 | 0 | 0 | 2000
20 | Director | 0 | 0 | 0 | 2000
20 | Programmer | 0 | 0 | 0 | 2000
20 | | 0 | 1 | 1 | 8000
30 | Architect | 0 | 0 | 0 | 3000
30 | Coding | 0 | 0 | 0 | 3000
30 | Director | 0 | 0 | 0 | 3000
30 | Programmer | 0 | 0 | 0 | 3000
30 | | 0 | 1 | 1 | 12000
40 | Architect | 0 | 0 | 0 | 4000
40 | Coding | 0 | 0 | 0 | 4000
40 | Director | 0 | 0 | 0 | 4000
40 | Programmer | 0 | 0 | 0 | 4000
40 | | 0 | 1 | 1 | 16000
| | 1 | 1 | 3 | 40000
(21 rows)