试验一、行转列。查询各个部门每个工资段的人数。
with emp_dept as (select dname, empno,sal from emp a join dept b using (deptno)) select * from emp_dept pivot (count(empno) as quantity for sal in (2450 as p2450,1300 as p1300,3000 as p3000,2975 as p2975,800 as p800)) order by dname;
得到结果:
DNAME P2450_QUANTITY P1300_QUANTITY P3000_QUANTITY P2975_QUANTITY P800_QUANTITY 1 ACCOUNTING 1 1 0 0 0 2 RESEARCH 0 0 2 1 1 3 SALES 0 0 0 0 0
比较
通过分组来查询
select dname, sal, count(empno) from emp a join dept b using (deptno) where sal in (2450, 1300, 300, 2975, 800) group by dname, sal
得到结果
DNAME SAL COUNT(EMPNO) 1 ACCOUNTING 1300 1 2 RESEARCH 800 1 3 ACCOUNTING 2450 1 4 RESEARCH 2975 1
二、
多列透视
增加一个聚合,派生列数会增加一倍。
with dept_salary as (select dname, empno, sal from emp a, dept b where a.deptno = b.deptno) select * from dept_salary pivot (count(empno) as sal, sum(nvl(sal, 0)) as sum_prc for sal in(800 as p800, 2975 as p2975, 1250 as p1250)) order by dname;
结果:略。