简体   繁体   English

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

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

I have a table called " Employee " 我有一个名为“ Employee ”的表

Employee tables has below columns 员工表具有以下列

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

T-SQL Query 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

Question: 题:

Employee table has below rows data. 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

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. 但是,如果我运行查询,我将看不到上述结果。我不确定我能否说出问题,但我想逐年查找所有员工的工作开始日期和结束日期 。我们将不胜感激。谢谢。

You can try OUTER APPLY : 您可以尝试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 ║
╚═════════╩═════════════════════╝

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM