我知道我们可以使用滞后函数来获取大于前一记录的30天的记录.
我有一个附加在图像as shown in image中的要求
第一行是开始,我使用该日期与连续的记录进行比较,一旦我找到一个记录&>=30天,我就需要获取该记录的日期并开始与连续的记录进行比较,直到我找到一个新的记录&>;=30天.
在结束后,这样做,我需要记录谁是30天间隔或空(第一个记录)
在SQL中,我们有什么方法可以实现这一点吗?
我try 使用LAG函数,但这将仅与前一条记录进行比较,这将导致从第一条记录起>;=30天的记录被删除.
declare @Payment table
(
PersonId int
, fromdate date
, todate date
)
insert @Payment
(PersonId, fromdate , todate )
values (1, '07/05/2014' , '07/06/2014' )
,(1, '07/15/2014' , '07/16/2014' )
,(1, '09/23/2014' , '09/24/2014')
,(1, '10/15/2014' , '10/16/2014')
,(1, '10/30/2014' , '10/31/2014')
,(2, '07/20/2014' , '07/25/2014')
,(2, '08/20/2014' , '08/21/2014')
,(2, '09/21/2014' , '09/22/2014')
select * from @Payment
;with cte as
(select PersonId , fromdate , todate
,datediff(d
, lag(todate) over (partition by PersonId order by fromdate)
, fromdate)DaysSinceLastindex
from @Payment )
select PersonId , fromdate , todate , DaysSinceLastindex
from cte
where DaysSinceLastindex >= 30 or DaysSinceLastindex is null
预期输出如所附图像enter image description here所示