查找在sql server 2008中具有相同id和不同开始和结束日期的员工每月的两个日期之间的日差异
问题描述:
我有一个表EmployeeProject
有三列empid
,startdate
,enddate
。查找在sql server 2008中具有相同id和不同开始和结束日期的员工每月的两个日期之间的日差异
我想获取相同empid
和不同startdate
和enddate
的每月两个日期之间的天数。
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 |
答
我假设你在你的例子有错误。
检查,看看是否是你需要(更改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
+0
非常感谢你!代码工作! :) – ABC
是什么,我的意思是用于显示月份名称的逻辑,当你说,对于一个特定的行一月或二月或等下属于什么....?请澄清。 – balaji
你的问题不清楚。你的提取条件是什么。明确询问你的预期结果是什么 – Mansoor
链接:http://dba.stackexchange.com/questions/125069/find-the-days-difference-between-two-dates -每月。 请引用链接。我希望按照上面的链接输出,但使用相同的employeeno和不同的startdate和enddate,因为我已经用上面的示例进行了介绍。 – ABC