T-Sql 每年获取员工开始和结束日期

Posted

技术标签:

【中文标题】T-Sql 每年获取员工开始和结束日期【英文标题】:T-Sql get Employees Start and end dates on a yearly basis 【发布时间】:2017-02-13 20:27:26 【问题描述】:

我有一个名为“Employee”的表

员工表有下面的列

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

T-SQL 查询

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

问题:

Employee 表有以下行数据。

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

根据上表行值,我的查询结果应如下所示

TheYear - EmployeeCountPerYear

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

但是,如果我运行我的查询,我看不到上面的结果。我不确定我是否能说出问题,但 我正在尝试逐年查找所有员工的工作开始日期和结束日期 .任何帮助将不胜感激。谢谢。

【问题讨论】:

【参考方案1】:

你可以试试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 这个。结果是:

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

【讨论】:

以上是关于T-Sql 每年获取员工开始和结束日期的主要内容,如果未能解决你的问题,请参考以下文章

在 T-SQL 中查找开始和结束日期(基于集合)

如何识别 T-SQL 中每个不同成员的多个开始和结束日期范围中的第一个间隙

查找每个员工的项目开始日期和结束日期(即开始日期和结束日期应该是连续的,在天/月/年中没有任何中断)

计算员工在开始和结束日期之间应报告工作的天数

启用夏令时时如何在 T-SQL 中获取一天的开始和结束?

如果基于开始日期的行之间没有更改,则合并员工历史记录