partition key | source id | row start date | row end date | row is current | id
--------------+-----------+----------------+--------------+----------------+-------
20150130001 | 1 | 1900-01-01 | 2015-01-30 | 0 | 1
20150131001 | 1 | 2015-01-31 | 2015-01-31 | 0 | 1
20150201001 | 1 | 2015-02-01 | 2015-02-01 | 0 | 1
20150213001 | 1 | 2015-02-02 | 2015-02-11 | 0 | 1
20150223001 | 1 | 2015-02-14 | 2015-02-23 | 0 | 1
20150303001 | 1 | 2015-02-24 | 2015-02-25 | 0 | 1
99991231001 | 1 | 2015-03-04 | 9999-12-31 | 1 | 1
如何找到行结束日期和下一行开始日期的行与同一个ID的差距> 1?
答案 0 :(得分:0)
将Table名称从Table1更改为您的表名,您应该得到一些结果。
With tblDates as (
select *,
LEAD( [row start date], 1) OVER(Order by [row start date]) as NextStartDate
from Table1 )
select *
from tblDates
Where DATEDIFF(d, [row end date], NextStartDate) > 1
答案 1 :(得分:0)
有了这类问题,我立即想到了EXISTS()。假设您的日期字段是datetime数据类型:
SELECT *
FROM MyTable t1
WHERE NOT EXISTS(
SELECT * FROM MyTable t2
WHERE t1.id=t2.id
AND DATEDIFF(dd, t1.[Row End Date], t2.[Row Start Date]) BETWEEN 0 AND 1
)
答案 2 :(得分:0)
如果您不使用SQL Server 2012+,则可以使用CROSS APPLY:
select *
from Table1 A
cross apply (
select min(rowstartdate)
from Table1 where rowstartdate > A.rowenddate
where id = A.id
) B(Minimo)
where DateDiff(DAY, A.rowenddate, B.Minimo) > 1
答案 3 :(得分:0)
我发现最简单的方法是:
SELECT *
FROM yourTable t
WHERE
DATEDIFF(DAY, t.endDate, (SELECT MIN(ti.startDate) FROM yourTable ti WHERE ti.partitionKey > t.partitionKey)) > 1
此查询只是说:当天行结束日期与当天下一个分区键的最低(第一个)开始日期之间存在差异的所有行都大于一(日)。