单一查询以检索员工的数量

时间:2015-04-16 20:25:13

标签: sql oracle pivot

我有一个包含以下字段的员工表

  

员工(id,name,joinedDate,salary,dept)

我想检索在每个部门过去1天,2天,3天和4天加入公司的所有员工的数量。请在下面的链接中查看我需要的结果。

  

样本结果:
  Sample Results

3 个答案:

答案 0 :(得分:2)

如果你想要它在过去的24小时,24到48小时之间等等......

SELECT dept,
       COUNT( CASE WHEN joiningDate BETWEEN SYSDATE - 1 AND SYSDATE     THEN 1 ELSE NULL END ) AS day1,
       COUNT( CASE WHEN joiningDate BETWEEN SYSDATE - 2 AND SYSDATE - 1 THEN 1 ELSE NULL END ) AS day2,
       COUNT( CASE WHEN joiningDate BETWEEN SYSDATE - 3 AND SYSDATE - 2 THEN 1 ELSE NULL END ) AS day3,
       COUNT( CASE WHEN joiningDate BETWEEN SYSDATE - 4 AND SYSDATE - 3 THEN 1 ELSE NULL END ) AS day4,
       COUNT( CASE WHEN joiningDate BETWEEN SYSDATE - 5 AND SYSDATE - 4 THEN 1 ELSE NULL END ) AS day5
FROM   Employee
GROUP BY dept;

如果你想要它昨天,2天前,3天前等,然后在TRUNC()的每个实例周围包裹SYSDATE

答案 1 :(得分:1)

以下内容可为您提供所需内容:

SELECT DEPT,
       SUM(CASE WHEN TRUNC(SYSDATE) - TRUNC(JOININGDATE) = 1 THEN 1 ELSE 0 END) AS day1,
       SUM(CASE WHEN TRUNC(SYSDATE) - TRUNC(JOININGDATE) = 2 THEN 1 ELSE 0 END) AS day2,
       SUM(CASE WHEN TRUNC(SYSDATE) - TRUNC(JOININGDATE) = 3 THEN 1 ELSE 0 END) AS day3,
       SUM(CASE WHEN TRUNC(SYSDATE) - TRUNC(JOININGDATE) = 4 THEN 1 ELSE 0 END) AS day4,
       SUM(CASE WHEN TRUNC(SYSDATE) - TRUNC(JOININGDATE) = 5 THEN 1 ELSE 0 END) AS day5
FROM EMPLOYEE
GROUP BY DEPT
ORDER BY DEPT;

SQLFiddle here

分享并享受。

答案 2 :(得分:1)

如果我们有透视标记,那么为什么不使用pivot

select * from (
    select dept, trunc(sysdate)-trunc(joiningDate) dt
      from employee where joiningDate >= trunc(sysdate)-5)
  pivot (count(1) for dt in (1 day1, 2 day2, 3 day3, 4 day4, 5 day5)) 
  order by dept

SQLFiddle demo