Oracle SQL- Flag records based on record's date vs history

后端 未结 4 458
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 06:01

This is my 1st post on the forum. Usually I was able to find what I needed - but to tell the truth - I am not really sure how to ask a correct question to the issue. Therefore,

4条回答
  •  自闭症患者
    2021-01-27 06:33

    Using a simplified "input" table... You can use the LAG() analytic function and a comparison condition to populate your last column. I assume your fiscalyearmonth is a number - if it is a character field, wrap fiscalyearmonth within TO_NUMBER(). (It would be much better if in fact you stored these as true Oracle dates, perhaps date 2016-06-01 instead of 201606, but I worked with what you have currently... and took advantage that in numeric format, "24 months ago" simply means "subtract 200").

    with inputs (linenum, idnum, fiscalyearmonth) as (
           select 1, 255, 201605 from dual union all
           select 2, 123, 201602 from dual union all
           select 3, 255, 201601 from dual union all
           select 4, 255, 201210 from dual
         )
    select linenum, idnum, fiscalyearmonth, 
           case when fiscalyearmonth 
                     - lag(fiscalyearmonth) 
                               over (partition by idnum order by fiscalyearmonth) < 200
                then 'Existing' else 'New' end         as flag
    from   inputs
    order by linenum;
    
    
       LINENUM      IDNUM FISCALYEARMONTH FLAG
    ---------- ---------- --------------- --------
             1        255          201605 Existing
             2        123          201602 New
             3        255          201601 New
             4        255          201210 New
    

提交回复
热议问题