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

后端 未结 4 480
伪装坚强ぢ
伪装坚强ぢ 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:38

    You can achieve using row_number() function as below... modify as per your need...I assumed 2 years (means previous 24 months from sysdate ). You can run the sub-queries separately to check how its working.

    Select 
    "REGION"
    ,"COUNTRY"
    ,"IDNum"
    ,"CUSTOMER"
    ,"BUSSINESS"
    ,"FISCALYEARMONTH"
    ,"FISCALYEAR"
    ,"VALUE"
    , ( case when ( TXNNO = 1 or TOTAL_TXN_LAST24MTH = 0 ) then 'New' else 'Existing' end ) as "HISTORICAL_PURCHASE_FLAG"  -- if no txn in last 24 month or its first txn then 'new' else 'existing'
    from
    (
      select 
      SubQry."REGION"
      , SubQry."COUNTRY"
      , SubQry."IDNum"
      , SubQry."CUSTOMER"
      , SubQry."BUSSINESS"
      , SubQry."FISCALYEARMONTH"
      , SUBQRY."FISCALYEAR"
      , SUBQRY."VALUE"
      , ROW_NUMBER() over (partition by SUBQRY."REGION",SUBQRY."COUNTRY",SUBQRY."IDNum",SUBQRY."CUSTOMER",SUBQRY."BUSSINESS" order by SUBQRY."FISCALYEARMONTH") as TXNNO,
      , SUM(case when (TO_NUMBER(TO_CHAR(sysdate,'YYYYMM')) - SUBQRY."FISCALYEARMONTH") < 24 then 1 else 0 end) as TOTAL_TXN_LAST24MTH
      From
      (
        SELECT
        T1."REGION"
        , T1."COUNTRY"
        , T1."IDNum"
        , T1."CUSTOMER"
        , T1."BUSSINESS"
        , T3."FISCALYEARMONTH"
        , T3."FISCALYEAR"
        , SUM(T4."VALUE") as VALUE
        FROM
        "DATABASE"."SALES" T4
        , "DATABASE"."CUSTOMER" T1
        , "DATABASE"."PRODUCT" T2
        , "DATABASE"."TIME" T3
        WHERE
        T4."CUSTOMERID" = T1."CUSTOMERID"
        AND T4."PRODUCTID" = T2."PRODUCTID"
        AND T4."DATEID" = T3."DATEID"
        AND T3."FISCALYEAR" IN ('2016')
        AND T1."COUNTRY" IN ('ENGLAND', 'France')
        GROUP BY
        T1."REGION"
        , T1."COUNTRY"
        , T1."IDNum"
        , T1."CUSTOMER"
        , T1."BUSSINESS"
        , T3."FISCALYEARMONTH"
        , T3."FISCALYEAR"
      ) SUBQRY
    );
    

提交回复
热议问题