I have a Microsoft SQL database with all past and present employees with their start and leave date. I would like to know how many employees were active each month in the past years.
While I did find a solution, I was wondering if there is a better one. I eventually want to create a dashboard with not just this one timeline but lots of similar ones and always aggregating the data in the way I did seems too complex.
Here is an example table similar to the one I want to use:
employee_id | first_name | last_name | start_date | leave_date |
---|---|---|---|---|
1 | Example | User | 2022-12-28 | 2023-05-30 |
2 | Second | Example | 2023-01-14 | 2023-12-31 |
3 | Third | Try | 2023-02-05 | 2024-04-15 |
This is the script I wrote. It gives the correct results I think, however, it seems quite complicated to me for something I thought was a pretty straight forward requirement.
DECLARE @startDate date = '2022-11-01';
CREATE TABLE #temp (
month_ date,
nb_employees int
)
WHILE @startDate < CURRENT_TIMESTAMP
BEGIN
INSERT INTO #temp
SELECT @startDate, COUNT(employee_id)
FROM employee_example
WHERE 1=1
AND (YEAR(start_date) < YEAR(@startDate)
OR (YEAR(start_date) = YEAR(@startDate) AND MONTH(start_date) <= MONTH(@startDate)))
AND (YEAR(leave_date) > YEAR(@startDate)
OR (YEAR(leave_date) = YEAR(@startDate) AND MONTH(leave_date) >= MONTH(@startDate)))
SET @startDate = DATEADD(month,1,@startDate)
END
SELECT * FROM #temp
DROP TABLE #temp
The result looks like this:
month_ | nb_employees |
---|---|
2022-11-01 | 0 |
2022-12-01 | 1 |
2023-01-01 | 2 |
2023-02-01 | 3 |
2023-03-01 | 3 |
2023-04-01 | 3 |
2023-05-01 | 3 |
2023-06-01 | 2 |
… | … |
ahtan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1