两个日期之间按月分组

Group By Month between two dates

我有一个 table 列出了所有员工及其各自的开始和结束日期

我希望能够统计每个月的活跃员工数。有没有办法通过单个查询(例如 groupBy)而不是每个月生成多个查询来做到这一点?

    =================================
    Employee ID   | StartDt      | EndDt
    123           | 01 Feb 2022  |  
    234           | 01 jan 2022  | 28 Feb 2022
    456           | 01 dec 2021  | 28 Feb 2022

举个例子,上面的table应该是return:

您可以生成一个日历并加入其中:

WITH calendar (month) AS (
  SELECT ADD_MONTHS(min_startdt, LEVEL - 1)
  FROM   (
    SELECT MIN(startdt) AS min_startdt,
           MAX(COALESCE(enddt, SYSDATE)) AS max_enddt
    FROM   employees
  )
  CONNECT BY LEVEL - 1 <= MONTHS_BETWEEN(max_enddt, min_startdt)
)
SELECT c.month,
       COUNT(e.employee_id)
FROM   calendar c
       LEFT OUTER JOIN employees e
       ON (e.startdt <= c.month AND (c.month <= e.enddt OR e.enddt IS NULL))
GROUP BY
       c.month

其中,对于示例数据:

CREATE TABLE employees (Employee_ID, StartDt, EndDt ) AS
SELECT 123, DATE '2022-02-01', NULL FROM DUAL UNION ALL
SELECT 234, DATE '2022-01-01', DATE '2022-02-28' FROM DUAL UNION ALL
SELECT 456, DATE '2021-12-01', DATE '2022-02-28' FROM DUAL;

输出:

MONTH COUNT(E.EMPLOYEE_ID)
2021-12-01 00:00:00 1
2022-01-01 00:00:00 2
2022-02-01 00:00:00 3
2022-03-01 00:00:00 1
2022-04-01 00:00:00 1

db<>fiddle here