2017-05-24 40 views
1

我有以下結構(發生表)表之間的天數:MS SQL SERVER 2014:獲取紀錄

ID EmployeeID  DateOfOccurrence 
-------------------------------------- 
1  999999   2017-02-14 
2  999999   2017-03-02 
3  999999   2017-03-23 
4  999999   2017-05-10 

我想創建一個查詢返回的結果(由僱員分組) :

999999  2017-02-14 to 2017-03-02  16 days 
999999  2017-03-02 to 2017-03-23  21 days 
999999  2017-03-23 to 2017-05-10  48 days 
999999  2017-05-10 to <today>  xx days 

* <today> = current day (i.e., getdate()) 

感謝您提前給予的幫助。

+0

的日期總是順序(由ID排序) – scsimon

+0

沒有他們不是。員工發生事故可能存在差距。每天早上爲所有員工添加事件(如果他們有一個)。 – klbass68

+1

爲什麼是第一排16天,但第二排20天(而不是21)? – SqlZim

回答

1

使用concat()lead()isnull()datediff()

select 
    id 
    , range = concat(
     convert(char(10),dateofoccurence,120) 
    , ' to ' 
    , convert(char(10),isnull(lead(dateofoccurence) over (partition by employeeid order by dateofoccurence),getdate()),120) 
) 
    , days = concat(
     datediff(
     day 
     , dateofoccurence 
     , isnull(lead(dateofoccurence) over (partition by employeeid order by dateofoccurence),getdate()) 
    ) 
    , ' days') 
from t 

rextester演示:http://rextester.com/FNQ48539

回報:

+----+--------------------------+---------+ 
| id |   range   | days | 
+----+--------------------------+---------+ 
| 1 | 2017-02-14 to 2017-03-02 | 16 days | 
| 2 | 2017-03-02 to 2017-03-23 | 21 days | 
| 3 | 2017-03-23 to 2017-05-10 | 48 days | 
| 4 | 2017-05-10 to 2017-05-24 | 14 days | 
+----+--------------------------+---------+ 
+0

完成工作。非常感謝。 – klbass68

+0

@ klbass68樂意幫忙! – SqlZim

+0

你鼓掌我的破譯技巧...你的更好+1 – scsimon