帮助查询

时间:2010-05-24 12:56:37

标签: oracle select

如何在Oracle的EMP表中列出有两个职员或三个经理的部门?

1 个答案:

答案 0 :(得分:7)

有很多方法可以获得这个结果。这是一个解决方案:

SQL> select deptno
  2         , mgr_count
  3         , clerk_count
  4  from
  5        ( select deptno
  6                 , sum ( case when job = 'MANAGER' then 1 else 0 end ) as mgr_count
  7                 , sum ( case when job = 'CLERK' then 1 else 0 end ) as clerk_count
  8          from emp
  9          group by deptno )
 10  where mgr_count > 3
 11  or clerk_count > 2
 12  /

    DEPTNO  MGR_COUNT CLERK_COUNT
---------- ---------- -----------
        30          3           5
        50          4           0

SQL>

这是一种略有不同的方法:

SQL> select * from
  2      ( select deptno
  3         , job
  4         , count(*) as cnt
  5      from emp
  6      group by deptno, job
  7      )
  8  where ( job = 'MANAGER' and cnt >= 3 )
  9  or ( job = 'CLERK' and cnt >= 2 )
 10  /

    DEPTNO JOB              CNT
---------- --------- ----------
        20 CLERK              2
        30 CLERK              5
        30 MANAGER            3
        50 MANAGER            4

SQL>