我有一个表,该表存储对象进度的连续周期的开始日期和结束日期。这是为了跟踪每个对象何时进入其进度的下一步
例如:
ObjectNum | Stage | StartDate | EndDate
1 |1 |2018-01-01 | 2018-02-24
1 |2 |2018-02-25 |
2 |1 |2018-01-01 |
SQL中是否有一种方法可以搜索此表并找到任何对象,其中一个阶段的结束日期与下一个连续阶段的开始之间的差超过1天?
亲切的问候
马特
答案 0 :(得分:3)
您可以在ObjectNum
和Stage
上将表与其自身连接,然后进行测试:
SELECT
t1.ObjectNum,
t1.Stage,
t1.StartDate,
t1.EndDate,
DATEDIFF("D", t1.EndDate, t2.StartDate) as StageGapInDays
FROM table t1
INNER JOIN table t2
ON t1.ObjectNum = t2.ObjectNum
AND t1.Stage + 1 = t2.Stage
Where StageGapInDays > 1
您还可以在子查询中使用LEAD()
窗口函数,因此只需要扫描一次表并避免联接:
SELECT *
FROM
(
SELECT
ObjectNum,
Stage,
StartDate,
EndDate,
DATEDIFF(day, EndDate, LEAD(StartDate) OVER (PARTITION BY ObjectNum ORDER BY Stage)) as StageGapInDays
FROM table
) subquery
Where StageGapInDays > 1
第二个将捕获Stage 1
,否 Stage 2
,然后是Stage 3
和{{ {1}}大于一天。第一个查询无法解决这种情况。
答案 1 :(得分:0)
针对对此感兴趣的人进行更新。考虑到Lead()在SQL2008中不起作用,这是我采用的解决方案
Select ObjectNum from Object m join
(SELECT ObjectNum, StartDate, EndDate, row_number() over (PARTITION by ObjectNum order by StartDate asc)as Row from STATHIS) s1
on s1.ObjectNum = m.ObjectNum
join
(SELECT ObjectNum, StartDate, EndDate, row_number() over (PARTITION by ObjectNum order by StartDate asc)as Row from STATHIS) s2
on s1.Row +1 = s2.Row and s1.ObjectNum = s2.ObjectNum
where DATEDIFF(DAY,s1.EndDate,s2.StartDate) > 1