I'm trying to do something similar to this thread How to get number of employees per year
The difference is that I need the headcount by month and also compute the number of leavers.
I have slightly modified the query so that instead of [year], I get [year-month]. So I convert the date into a string and extract the first 6 characters (YYYYMM) and convert it to an integer.
DECLARE @FromYear int, @ToYear int
SELECT @FromYear = 201801,
@ToYear = convert(int,LEFT(CONVERT(char,GETDATE(),112),6))
FROM [Airconnect].[dbo].[CoreNZ]
;WITH CTE AS
(
SELECT @FromYear As TheYear
UNION ALL
SELECT TheYear + 1
FROM CTE
WHERE TheYear < @ToYear
)
SELECT TheYear as [Year],
COUNT
(
CASE WHEN TheYear <= convert(int,LEFT(CONVERT(char,COALESCE([Staff_End_Date], GETDATE()),112),6)) THEN
1
END
) As [No. of Employees.]
FROM CTE
INNER JOIN [dbo].[CoreNZ] ON(TheYear >= convert(int,LEFT(CONVERT(char,Start_Date,112),6)))
GROUP BY TheYear
I get the following message:
Msg 530, Level 16, State 1, Line 8 The statement terminated. The maximum recursion 100 has been exhausted before statement completion.