将创建多个寄存器从一个表插入到另一个表

时间:2018-07-09 16:29:50

标签: sql

我有下表

Eployee ID     Start Month       End Month
1              3/4/2013          26/11/2017
2              20/12/2014
3              1/8/2017          30/01/2018

我需要创建一个新表,其中包含员工截至工作的每个月(如果没有工作月仍在工作)每月包含一个寄存器的表

我需要得到这样的东西

Month       Employee ID
4/2013          1
5/2013          1
...
11/2017         1
12/2014         2
1/2015          2
...
current month   2
8/2017          3
...
1/2018          3

1 个答案:

答案 0 :(得分:0)

如果您正在使用SQL Server,那么递归 cte是一种选择:

with t as (
     select EmployeeID, StartMonth, EndMonth
     from table
     where EndMonth is not null
     union all
     select EmployeeID, dateadd(mm, 1, StartMonth), EndMonth
     from t
     where StartMonth < EndMonth
)

select EmployeeID, concat(datepart(mm, StartMonth), '/', datepart(year, StartMonth)) as Month
from t
union all
select EmployeeID, concat(datepart(mm, getdate()), '/', datepart(year, getdate()))
from table
where EndMonth is null
order by EmployeeID;