我的表格的每一行都包含一个引用和一个日期。我试图找到一个日期和前一个日期之间的天数。
让我们来看下面的例子:
CREATE TABLE #Test
(
Ref NVARCHAR(100) NOT NULL,
Dat DATETIME NOT NULL
)
INSERT INTO #Test ( Ref, Dat )
VALUES ( N'ABC123', GETDATE() ),
( N'DHI458', GETDATE() + 1 ),
( N'HGYU556', GETDATE() - 3 ),
( N'UUU021', GETDATE() + 17 )
我想得到类似的东西:
UUU021 2017-01-01 17:27:00.720 17
DHI458 2016-12-16 17:27:00.720 1
ABC123 2016-12-15 17:27:00.720 3
HGYU556 2016-12-12 17:27:00.720 NULL
在一个选择中。可能吗?我正在使用SQL Server 2008.
答案 0 :(得分:2)
SQL Server 2012+支持lag()
。在SQL Server 2008中,您有几个选项 - 没有一个真正好。我会选择outer apply
:
select t.*,
datediff(day, tprev.date, t.date) as diff
from #test t outer apply
(select top 1 t2.*
from #test t2
where t2.date < t.date
order by t2.date desc
) tprev;
答案 1 :(得分:0)
戈登的方法很扎实,但这是另一个
with CTE as
(
select Ref, Dat, row_number() over (order by Dat desc) as DatO
from #Test
)
select A1.Ref, A1.Dat, A1.Dat-A2.Dat as Diff
from CTE A1
left join CTE A2
on A1.DatO = A2.DatO - 1;
答案 2 :(得分:0)
我通常喜欢自我加入,直到有效的2个表被1行偏移:
select t1.Ref, t1.Dat. datediff(dd, t1.Dat, t2.Dat) as diff
from #Test as t1
inner join #Test as t2
on t2.Dat > t1.Dat
and not exists (
select 1
from #Test as t3
where t3.Dat > t1.Dat
and t3.Dat < t2.Dat
)
order by t1.Dat desc