발생 수 사이의 일 수를 가져옵니다 :MS SQL 서버 2014 : 나는 다음과 같은 구조 (발생 표)이있는 테이블이
ID EmployeeID DateOfOccurrence
--------------------------------------
1 999999 2017-02-14
2 999999 2017-03-02
3 999999 2017-03-23
4 999999 2017-05-10
가 나는 결과를 반환하는 쿼리를 만들 싶습니다을 (직원 ID별로 그룹화) :
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())
미리 감사드립니다.
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
반환 : concat()
, lead()
, isnull()
및 datediff()
사용
이 날짜는 항상 연속 (ID로 정렬)됩니다 – scsimon
아니가 그렇지 않습니다. 직원의 발생 간격에는 차이가있을 수 있습니다. 발생 건수는 모든 직원에게 (매일 직원이있는 경우) 추가됩니다. – klbass68
왜 첫 번째 행은 16 일이지만 두 번째 행은 20 일 (21 대신)입니까? – SqlZim