LEAD功能-Oracle

时间:2018-08-09 21:39:58

标签: sql database oracle plsql

我想比较一个开始日期和一个结束日期:

示例:

  1. start_date: 2017-12-13 00:00:00    End_date: 2017-12-13 09:44:00
  2. start_date: 2017-12-13 09:44:00    End_date: 2017-12-13 16:19:00
  3. start_Date: 2017-12-13 16:19:00    End_date: 2017-12-18 00:00:00

我想比较start_date第2行和end_date第1行。如果它们不匹配,请执行一些操作。下面的牵头功能没有给我我想要的东西。请鸣叫并提供帮助。查询工作后,我将其循环并遍历整个表。谢谢

    SELECT start_Date, end_date,
      LEAD (start_Date, 1) OVER (ORDER BY start_Date) AS next_start_DAte
      from    my_table
      where   start_date >= '2017-12-01' 
      AND     END_DATE < '2018-08-01'
      AND     FILE_ID IS NULL
      ORDER BY UNIT_ID, START_DATE;

2 个答案:

答案 0 :(得分:1)

您可以仅使用not exists查找与“下一个”行不完全匹配的行:

select t.*
from my_table t
where not exists (select 1
                  from my_table t2
                  where t2.start_date = t.end_date
                 );

这将始终返回表的最后一行,但该行符合您描述的条件。

答案 1 :(得分:0)

您可以使用以下查询

SELECT START_DATE ,END_DATE, 
--If they dont match do something. 
case when  trunc(next_date) <> trunc(end_date) then 1 else 2 end dosomething 
FROM (
SELECT leadtest.*, lead(start_date, 1) over (order  by start_date) next_date FROM leadtest)
;

希望这会有所帮助!