比较2个连续的行 - 创建和填充列符合条件

时间:2017-12-13 00:09:24

标签: sql oracle

我想比较连续的行,如果满足以下条件,我想创建并填充一个名为Electronic_to_manual的新列,其中包含'Y'

这是我的查询

select distinct user_id, trans_id, status,date, source
from `table1`
where date >= '20171207'
order by user_id, trans_id, source asc, status desc

我基本上想要查看所有行,例如'%manual%',如果在之前的行中对于相同的user_id和trans_id组合,如果souce ='electronic',我想要填充该行的electronic_to_manual字段'Y'

见下面的例子。

user_id trans_id    Status  Date        Source          Electronic_to_manual (new column)   
123     1           Open    12/8/2017   Electronic  
123     1           Closed  12/8/2017   Electronic  
123     1           Closed  12/8/2017   Electronic  
123     1           Open    12/8/2017   Manual COB      Y    
123     1           Closed  12/9/2017   Manual COB  
456     1           Closed  12/8/2017   Manual COB  
456     23          Open    12/8/2017   Electronic  
456     23          Closed  12/8/2017   Manual Request  Y   
789     45          Open    12/8/2017   Electronic  
789     45          Closed  12/8/2017   Electronic  
789     45          Closed  12/8/2017   Electronic  

2 个答案:

答案 0 :(得分:0)

您可以按以下方式使用LAG功能:

SELECT *
      ,CASE WHEN (LOWER(source) LIKE '%manual%'
                   AND LOWER(prev_source) LIKE '%electronic%')
            THEN 'Y'
            ELSE NULL END
       AS Electronic_to_manual

  FROM (SELECT *
              ,LAG(source) OVER (PARTITION BY user_id
                                 ORDER BY trans_id, source, status)
               AS prev_source
          FROM table1
          ORDER BY user_id
        ) x

答案 1 :(得分:0)

要求更新:

update Table1
set electronic_to_manual = 'Y'
where exists (
      select 1
      from (
           select t.*
             , lag(t.source) over(partition by t.user_id , t.trans_id order by t.source asc, t.status desc) prev_source
           from table1 t
           ) d
      where source like 'Manual%' and prev_source = 'Electronic'
      and table1.user_id = d.user_id
            and table1.trans_id = d.trans_id
            and table1.transdate = d.transdate
            and table1.source = d.source
     )

dbfiddle Demo here

select d.*
from (
     select t.*
       , lag(source) over(partition by user_id , trans_id order by source asc, status desc) prev_source
     from table1 t
     ) d
where source like 'Manual%' and prev_source = 'Electronic'
order by user_id , trans_id, source asc, status desc