原来的数据是:
期望的数据是:
sql语句:
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7369', 'SMITH', 'CLERK', '7902', '12/17/1980', '800', null, '20');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7499', 'ALLEN', 'SALESMAN', '7698', '2/20/1981', '1600', '300', '30');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7521', 'WARD', 'SALESMAN', '7698', '2/22/1981', '1250', '500', '30');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7566', 'JONES', 'MANAGER', '7839', '4/2/1981', '2975', null, '20');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7654', 'MARTIN', 'SALESMAN', '7698', '9/28/1981', '1250', '1400', '30');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7698', 'BLAKE', 'MANAGER', '7839', '5/1/1981', '2850', null, '30');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7782', 'CLARK', 'MANAGER', '7839', '6/9/1981', '2450', null, '10');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7788', 'SCOTT', 'ANALYST', '7566', '4/19/1987', '3000', null, '20');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7839', 'KING', 'PRESIDENT', null, '11/17/1981', '5000', null, '10');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7844', 'TURNER', 'SALESMAN', '7698', '9/8/1981', '1500', '0', '30');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7876', 'ADAMS', 'CLERK', '7788', '5/23/1987', '1100', null, '20');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7900', 'JAMES', 'CLERK', '7698', '12/3/1981', '950', null, '30');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7902', 'FORD', 'ANALYST', '7566', '12/3/1981', '3000', null, '20');
insert into emp (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)
values ('7934', 'MILLER', 'CLERK', '7782', '1/23/1982', '1300', null, '10');
代码实现:
---方法一
select t.job, count(decode(t.deptno, '10', 1)) as "10(DEPTNO)",
count(decode(t.deptno, '20', 1)) as "20(DEPTNO)",
count(decode(t.deptno, '30', 1)) as "30(DEPTNO)",
count(decode(t.deptno, '40', 1)) as "40(DEPTNO)"
from emp t
group by t.job;
--方法二
with tmp_tab as
(select t.job, t.deptno from emp t)
select * from tmp_tab t pivot (count(1) for deptno in(10, 20, 30, 40));