我在sql server 2012中有一个表,它有一个ID,startDate和EndDate,如果id是1,2,3和4各自的日期,我想得到ID = 1的endDate之间的区别和ID = 2的startDate等等我似乎无法获得IDEA,任何帮助都会非常好,在此提前感谢:)
答案 0 :(得分:2)
使用lead()
窗口功能:
$cred = Get-Credential;
Invoke-Command -Credential $cred ...
select t.*
, DaysUntilNextStartDate = datediff(day,t.enddate,lead(startdate) over (order by id))+1
from t
使用自联接(如果select t.*
, DaysUntilNextStartDate = datediff(day,t.enddate,n.startdate)+1
from t
outer apply (
select top 1
i.startdate
from t as i
where i.id > t.id
order by i.id asc
) as n
始终是连续的,没有间隙):
id