如何获得每年的员工数量

时间:2015-06-18 05:47:07

标签: sql-server sql-server-2008 tsql

我有一张名为Mst_Employee的表格。字段是:

Emp_No | Emp_Name | Emp_JoiningDate | Emp_ResignedDate | Emp_Status

每年有人加入或辞职,我如何获得每年的员工人数? (加入和辞职包括年度)

E.g。结果应如下所示:

Year   No. of Employees.
------------------------
2011   125
2012   130
2013   100

2 个答案:

答案 0 :(得分:0)

解决问题的一种方法是使用recursive cte和分组:

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

答案 1 :(得分:0)

您可以通过以下方式实现此目的:

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