0

I have a table called Mst_Employee. The fields are:

Emp_No | Emp_Name | Emp_JoiningDate | Emp_ResignedDate | Emp_Status

How do I get the No. of Employees by year for each year somebody joined or resigned? (Joined and Resigned includes by year)

E.g. result should look like this:

Year   No. of Employees.
------------------------
2011   125
2012   130
2013   100
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
user3069097
  • 59
  • 1
  • 12

2 Answers2

1

One way to solve it is with a recursive cte and group by:

DECLARE @FromYear int, @ToYear int

SELECT @FromYear = YEAR(MIN(Emp_JoiningDate)),
       @ToYear = YEAR(GETDATE())
FROM Mst_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(Emp_ResignedDate, GETDATE())) THEN 
           1 
       END
       ) As [No. of Employees.]
FROM CTE
INNER JOIN Mst_Employee ON(TheYear >= YEAR(Emp_JoiningDate))
GROUP BY TheYear

See fiddle here

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0

You can achieve this with:

select y as [Year], count(*) as [No. of Employees.]  
from(select Emp_No, YEAR(Emp_JoiningDate) as y from Mst_Employee
     union 
     select Emp_No, YEAR(Emp_ResignedDate) from Mst_Employee 
     where Emp_ResignedDate is not null)t
group by y
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
  • Thanks Giorgi for your query i add slightly as per my structure and got the result select y as [Year], count(*) as [No. of Employees.] from(select Emp_No, YEAR(Emp_JoiningDate) as y from Mst_Employee where Emp_ResignedDate is null union select Emp_No, YEAR(Emp_ResignedDate) from Mst_Employee where Emp_ResignedDate is not null)t group by y – user3069097 Jun 18 '15 at 08:20
  • Dear Giorgi, Another thing i'm looking for the Columns to be display Year, No. of Joined and No. of resign please help on this. – user3069097 Jun 30 '15 at 05:19
  • Thanks for your query. Just what I needed – Fokwa Best Jun 07 '19 at 15:27