【问题标题】:Consecutive records in oracle SQLoracle SQL中的连续记录
【发布时间】:2017-02-07 16:58:10
【问题描述】:

我有一个类似的问题想在这里发布。 需要连续缺勤 3 天或以上的员工。假设所有的日子都是工作日,周六/周日/任何其他日子没有假期。

在下表中,我需要结果集中的 20342123 和 20311111。 员工 20311333 已请了 4 次休假,但它们不是连续的。

提前感谢您的帮助。

Emp Id     |  AsofDate      | Comment 
----------------------------------
20342123   |  1-JAN-2017| Absent 
20342123   |  2-JAN-2017| Absent 
20342123   |  3-JAN-2017| Absent
20311111   |  1-JAN-2017| Absent 
20311111   |  2-JAN-2017| Absent 
20311111   |  3-JAN-2017| Absent
20311333   |  5-JAN-2017| Absent
20311333   |  6-JAN-2017| Absent
20311333   |  8-JAN-2017| Absent 
20311333   |  9-JAN-2017| Absent
20322222   |  1-JAN-2017| Absent
20322222   |  2-JAN-2017| Absent

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    虽然您可以应用“间隙和岛屿”解决方案,但我认为lag()/lead() 对于这个问题更简单:

    select distinct emp_id
    from (select t.*,
                 lead(date) over (partition by empid order by date) as date_1,
                 lead(date, 2) over (partition by empid order by date) as date_2
          from t
          where comment = 'Absent'  -- not sure if this is important
         ) t
    where date_1 = date + 1 and date_2 = date + 2;
    

    【讨论】:

    • 感谢戈登·林诺夫。我在那里错过了一分。正确的问题是 '3 或更多连续出现...' 。是的,comment = 'Absent' 是必需的,因为其他值也会存在。
    • @DevadasWagle 。 . .这会连续找到 3 个。因此它会连续找到 3 个或更多。
    • 抱歉,即使连续 3 行也无法正常工作。我知道表中有记录但没有出现在输出中。
    • Gordon Linoff :我在这里搜索了类似的一个:stackoverflow.com/questions/31660093/… 但是当我们希望连续出现超过 3 次时,用户也说查询不起作用。
    • @DevadasWagle 。 . .您的date 列是否可能包含时间组件?
    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 2020-06-18
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    相关资源
    最近更新 更多