首页 > 代码库 > 7.7 使用rollup子句
7.7 使用rollup子句
--向rollup传递一列
select division_id,sum(salary) from employees2 group by rollup(division_id);
--向rollup传递多列
select division_id,job_id,sum(salary) from employees2 group by rollup(division_id,job_id);
--修改传递给rollup的列的位置
select job_id,division_id,sum(salary) from employees2 group by rollup(job_id,division_id);
--向cube传递一列
select division_id,sum(salary) from employees2 group by cube(division_id);
--向cube传递多列
select division_id,job_id,sum(salary) from employees2 group by cube(division_id,job_id);
--修改传递给cube的列的位置
select job_id,division_id,sum(salary) from employees2 group by cube(job_id,division_id);
--grouping如果列值为空,那么返回1,如果列值非空,则返回0
select grouping(division_id),division_id,sum(salary) from employees2 group by rollup(division_id);
--使用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);
--使用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);
--使用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);
--使用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);
--使用grouping sets子句只返回小计记录
select division_id,job_id,sum(salary) from employees2 group by grouping sets(division_id,job_id);
--grouping_id
select division_id,
job_id,
grouping_id(division_id) div_grp,
grouping_id(job_id) job_grp,
grouping_id(division_id, job_id) grp_id,
sum(salary)
from employees2
group by cube(division_id, job_id);
--使用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;
--
select division_id, job_id, sum(salary)
from employees2
group by division_id, rollup(division_id, job_id);
--group_id消除group by子句返回的重复记录
select division_id, job_id, group_id(), sum(salary)
from employees2
group by division_id, rollup(division_id, job_id);
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子句