日期:2014-05-17 浏览次数:20979 次
DROP TABLE dept;
CREATE TABLE dept(deptid NUMBER,deptname nvarchar2(20),deptpid NUMBER);
INSERT INTO dept
select 1 deptid,'部门一' deptname, 0 deptpid from dual
union all select 2,'部门二', 1 from dual
union all select 3,'部门三', 1 from dual
union all select 4,'部门四', 1 from dual
union all select 5,'部门五', 2 from dual;
DROP TABLE people;
CREATE TABLE people(peopleid NUMBER,deptid NUMBER,peopletype NVARCHAR2(20));
INSERT INTO people
select 1 peopleid,1 deptid,'typeA' peopletype from dual
union all select 2,2,'typeB' from dual
union all select 3,3,'typeC' from dual
union all select 4,4,'typeD' from dual
union all select 5,5,'typeB' from dual
union all select 6,2,'typeB' from dual;
COMMIT;
SELECT deptid,deptname
,SUM(NVL(CASE WHEN peopletype='typeA' THEN 1 ELSE 0 END,0)) AS typeA
,SUM(NVL( CASE WHEN peopletype='typeB' THEN 1 ELSE 0 END,0)) AS typeB
,SUM(NVL( CASE WHEN peopletype='typeC' THEN 1 ELSE 0 END,0)) AS typeC
,SUM(NVL( CASE WHEN peopletype='typeD' THEN 1 ELSE 0 END,0)) AS typeD
FROM
(
SELECT a.deptid,deptname,peopletype,COUNT(*)
FROM dept a
LEFT JOIN people b
ON a.deptid=b.deptid
GROUP BY a.deptid,deptname,peopletype
) t
GROUP BY deptid,deptname
ORDER BY deptid;