单一查询以检索员工人数

Single Query to retrieve count of the employees

我有一名员工 table 具有以下字段

employee(id, name, joiningDate, salary, dept)

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

Sample result:

如果您想要在过去 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.

的每个实例周围

以下内容应该可以满足您的需求:

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

如果我们有数据透视标签,那为什么不使用 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