簡體   English   中英

SQL查詢可根據該范圍的行之前和之后的記錄轉換記錄集或記錄范圍

[英]SQL query which converts sets or range of records on the basis of record before and after rows of that range

假設這張桌子

Day Present Absent  Holiday
1/1/2019    1   0   0
1/2/2019    0   1   0
1/3/2019    0   0   1
1/4/2019    0   0   1
1/5/2019    0   0   1
1/6/2019    0   1   0
1/7/2019    1   0   0
1/8/2019    0   1   0
1/9/2019    0   0   1
1/10/2019   0   1   0

我想將缺席之間的所有假期標記為零,如果員工在假期之前和之后缺席,那么假期對他來說將成為缺席天數。 我不想使用循環,我想設置基本查詢方法。

作為select ,您可以使用lead()lag()

select t.*,
       (case when prev_absent = 0 and next_absent = 0 and holiday = 1
             then 0 else holiday
        end) as new_holiday
from (select t.*,
             lag(absent) over (order by day) as prev_absent,
             lead(absent) over (order by day) as next_absent
      from t
     ) t;

如果這樣做符合您的要求,則可以將其合並到update

with toupdate as (
      select t.*,
             (case when prev_absent = 0 and next_absent = 0 and holiday = 1
                   then 0 else holiday
              end) as new_holiday
      from (select t.*,
                   lag(absent) over (order by day) as prev_absent,
                   lead(absent) over (order by day) as next_absent
            from t
           ) t
     ) t
update toupdate
    set holiday = new_holiday
    where holiday <> new_holiday;

編輯:

您也可以使用join s來做到這一點:

select t.*,
       (case when tprev.absent = 0 and tnext.absent = 0 and t.holiday = 1
             then 0 else holiday
        end) as new_holiday
from t left join
     t tprev
     on tnext.day = dateadd(day, -1, t.day) left join
     t tnext
     on tprev.day = dateadd(day, 1, tprev.day)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM