2016-11-15 58 views
0

我有一個表EmployeeProject有三列empid,startdate,enddate查找在sql server 2008中具有相同id和不同開始和結束日期的員工每月的兩個日期之間的日差異

我想獲取相同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 | 
+0

是什麼,我的意思是用於顯示月份名稱的邏輯,當你說,對於一個特定的行一月或二月或等下屬於什麼....?請澄清。 – balaji

+0

你的問題不清楚。你的提取條件是什麼。明確詢問你的預期結果是什麼 – Mansoor

+0

鏈接:http://dba.stackexchange.com/questions/125069/find-the-days-difference-between-two-dates -每月。 請引用鏈接。我希望按照上面的鏈接輸出,但使用相同的employeeno和不同的startdate和enddate,因爲我已經用上面的示例進行了介紹。 – ABC

回答

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 
+0

非常感謝你!代碼工作! :) – ABC

相關問題