Skip to content
Advertisement

Group By Month between two dates

I have a table that lists all employees and their respective start and end dates

I want to be able to count the number of active employees in each month. Is there a way to do this via a single query (eg groupBy) rather than generating multiple queries for each month?

As an example, the table above should return:

  • Dec 2021: 1
  • Jan 2022: 2
  • Feb 2022: 3
  • Mar 2022: 1
  • Apr 2022: 1

Advertisement

Answer

You can generate a calendar and join to that:

Which, for the sample data:

Outputs:

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

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement