Soner
Soner

Reputation: 1282

T-Sql get Employees Start and end dates on a yearly basis

I have a table called "Employee"

Employee tables has below columns

Id (Identity)
EmploymentStartDate (datetime),
EmploymentEndDate (nullable datetime)

T-SQL Query

DECLARE @FromYear int, @ToYear int

SELECT @FromYear = YEAR(MIN(EmploymentStartDate)),
       @ToYear = YEAR(GETDATE())
FROM Employee

;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 <= YEAR(COALESCE(EmploymentEndDate, GETDATE())) THEN 
           1 
       END
       ) As [EmployeeCountPerYear]
FROM CTE
INNER JOIN Employee ON(TheYear >= YEAR(EmploymentStartDate))
GROUP BY TheYear

Question:

Employee table has below rows data.

Id - EmploymentStartDate  -  EmploymentEndDate
1  - '2012-10-10'         -   null
2  - '2014-10-10'         -   '2015-10-10'
3  - '2015-10-10'         -   null
4  - '2016-10-10'         -   null
5  - '2017-10-10'         -   null

According to above table row values result should be as below on my query

TheYear - EmployeeCountPerYear

2012    -  1
2013    -  1
2014    -  2
2015    -  3 (Because EmploymentEndDate has one employee that worked in 2015)
2016    -  3
2017    -  4

However if i run my query i can not see result as above.I am not sure i can tell the problem but i am trying to find all employees Working started date and Ended date year by year.Any help will be appreated.Thank you.

Upvotes: 0

Views: 369

Answers (1)

Lamak
Lamak

Reputation: 70638

You can try OUTER APPLY:

DECLARE @FromYear int, @ToYear int;

SELECT @FromYear = YEAR(MIN(EmploymentStartDate)),
       @ToYear = YEAR(GETDATE())
FROM Employee;

WITH CTE AS 
(
    SELECT @FromYear As TheYear
    UNION ALL
    SELECT TheYear + 1
    FROM CTE
    WHERE TheYear < @ToYear
)
SELECT *
FROM CTE A
OUTER APPLY(SELECT COUNT(*) EmploymentStartDate  
            FROM dbo.Employee
            WHERE A.TheYear 
            BETWEEN YEAR(EmploymentStartDate) AND YEAR(ISNULL(EmploymentEndDate,GETDATE()))) B;

Here is a demo of this. And the results are:

╔═════════╦═════════════════════╗
║ TheYear ║ EmploymentStartDate ║
╠═════════╬═════════════════════╣
║    2012 ║                   1 ║
║    2013 ║                   1 ║
║    2014 ║                   2 ║
║    2015 ║                   3 ║
║    2016 ║                   3 ║
║    2017 ║                   4 ║
╚═════════╩═════════════════════╝

Upvotes: 3

Related Questions