T-Sql每年为员工提供开始和结束日期

时间:2017-02-13 20:27:27

标签: sql sql-server tsql

我有一张名为“员工

的表格

员工表格位于列

之下
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

问题:

员工表下面有行数据。

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 个答案:

答案 0 :(得分:3)

您可以尝试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 ║
╚═════════╩═════════════════════╝