7.7 使用rollup子句

时间:2021-12-09 14:51:45

--向rollup传递一列
select division_id,sum(salary) from employees2 group by rollup(division_id);

7.7 使用rollup子句
--向rollup传递多列
select division_id,job_id,sum(salary) from employees2 group by rollup(division_id,job_id);

7.7 使用rollup子句
--修改传递给rollup的列的位置
select job_id,division_id,sum(salary) from employees2 group by rollup(job_id,division_id);

7.7 使用rollup子句

--向cube传递一列
select division_id,sum(salary) from employees2 group by cube(division_id);

7.7 使用rollup子句
--向cube传递多列
select division_id,job_id,sum(salary) from employees2 group by cube(division_id,job_id);

7.7 使用rollup子句
--修改传递给cube的列的位置
select job_id,division_id,sum(salary) from employees2 group by cube(job_id,division_id);

7.7 使用rollup子句

--grouping如果列值为空,那么返回1,如果列值非空,则返回0
select grouping(division_id),division_id,sum(salary) from employees2 group by rollup(division_id);

7.7 使用rollup子句
--使用decode转换grouping的一个列的值 rollup

select decode(grouping(division_id), 1, 'all divisions', division_id) div,

division_id,
sum(salary)
from employees2
group by rollup(division_id);

7.7 使用rollup子句
--使用decode转换grouping的多个列的值 rollup
select decode(grouping(division_id), 1, 'all divisions', division_id) div,
decode(grouping(job_id), 1, 'all jobs', job_id) job,
division_id,
sum(salary)
from employees2
group by rollup(division_id, job_id);

7.7 使用rollup子句
--使用decode转换grouping的一个列的值 cube

select decode(grouping(division_id), 1, 'all divisions', division_id) div,
division_id,
sum(salary)
from employees2
group by cube(division_id);

7.7 使用rollup子句

--使用decode转换grouping的多个列的值 cube
select decode(grouping(division_id), 1, 'all divisions', division_id) div,
decode(grouping(job_id), 1, 'all jobs', job_id) job,
division_id,
sum(salary)
from employees2
group by cube(division_id, job_id);
7.7 使用rollup子句
--使用grouping sets子句只返回小计记录
select division_id,job_id,sum(salary) from employees2 group by grouping sets(division_id,job_id);

7.7 使用rollup子句

--grouping_id

division_id和job_id两列都非空,返回0

division_id非空,job_id为空,返回1

division_id为空,job_id非空,返回2

division_id和job_id两列都为空,返回3

select division_id,
job_id,
grouping_id(division_id, job_id) grp_id,
sum(salary)
from employees2
group by cube(division_id, job_id);

7.7 使用rollup子句

--使用having过滤
select division_id,
job_id,
grouping_id(division_id, job_id) grp_id,
sum(salary)
from employees2
group by cube(division_id, job_id)
having grouping_id(division_id, job_id) > 0;

7.7 使用rollup子句

--在group by子句中多次使用一个列
select division_id, job_id, sum(salary)
from employees2
group by division_id, rollup(division_id, job_id);
7.7 使用rollup子句
--group_id消除group by子句返回的重复记录
select division_id, job_id, group_id(), sum(salary)
from employees2
group by division_id, rollup(division_id, job_id);

7.7 使用rollup子句
select division_id, job_id, group_id(), sum(salary)
from employees2
group by division_id, rollup(division_id, job_id) having group_id() = 0;

7.7 使用rollup子句