在sql server 2008中查找具有相同ID和不同开始日期和结束日期的员工每月两个日期之间的天数差异

时间:2016-11-15 07:26:37

标签: sql sql-server sql-server-2008 datediff

我有一个表EmployeeProject,其中包含三列empidstartdateenddate

我想获取每月两个日期之间的天数,使用相同的empid和不同的startdateenddate

Empid | Startdate | Enddate  |
-----------------------------
1     | 20160115  | 20160330 |
1     | 20160101  | 20161231 |
2     | 20161001  | 20161031 |
2     | 20161215  | 20170131 |

我希望输出如下:

Empid | StartDate | Enddate  | Monthname | Days |
------------------------------------------------
1     | 20160115  | 20160330 | Jan       | 15   |
1     | 20160115  | 20160330 | Feb       | 29   |
1     | 20160115  | 20160325 | Mar       | 25   |
1     | 20160101  | 20161229 | Jan       | 31   |
1     | 20160101  | 20161231 | Feb       | 29   |
2     | 20161001  | 20161031 | Oct       | 31   |
2     | 20161215  | 20170131 | Dec       | 15   |
2     | 20161215  | 20170131 | Jan       | 31   |

1 个答案:

答案 0 :(得分:1)

我认为你的例子中有错误。
检查一下,看看你是否需要(改变MyTable)

with        cte (Empid,Startdate,Enddate,month_offset,n) as 
            (
                select      t.Empid,t.Startdate,t.Enddate,datediff(month,t.Startdate,t.Enddate),1
                from        MyTable

                union all

                select      Empid,Startdate,Enddate,month_offset-1,n+1
                from        cte
                where       month_offset > 0
            )

select      Empid,Startdate,Enddate
           ,left(datename(month,dateadd(month,month_offset,Startdate)),3)   as Monthname 

           ,datediff 
            (
                day
               ,case month_offset when 0 then Startdate else dateadd(month,datediff(month,0,Startdate)+month_offset,0) end
               ,case n when 1 then Enddate else dateadd(month,datediff(month,0,Startdate)+month_offset+1,0) end
            )   as days



from        cte

order by    Empid,Startdate,Enddate
           ,case month_offset when 0 then Startdate else dateadd(month,datediff(month,0,Startdate)+month_offset,0) end