sql >> データベース >  >> RDS >> Oracle

OracleSQL-レコードの日付と履歴に基づいてレコードにフラグを立てます

    LAG を使用できます 機能:

    SELECT
    "REGION"
    , "COUNTRY"
    , "IDNum"
    , "CUSTOMER"
    , "BUSSINESS"
    , "FISCALYEARMONTH"
    , "FISCALYEAR"
    , SUM("VALUE") 
    , MAX(CASE WHEN to_date(prev_fym,'YYYYMM')  >= ADD_MONTHS (to_date("FISCALYEARMONTH",'YYYYMM'), -24) THEN 'Existing' 
               ELSE NULL END) "HISTORICAL_PURCHASE_FLAG"
    FROM
    (
        SELECT
        T1."REGION"
        , T1."COUNTRY"
        , T1."IDNum"
        , T1."CUSTOMER"
        , T1."BUSSINESS"
        , T3."FISCALYEARMONTH"
        , T3."FISCALYEAR"
        , T4."VALUE"
        , LAG ("FISCALYEARMONTH", 1) OVER (PARTITION BY T1."IDNum" ORDER BY T3."FISCALYEARMONTH" DESC) prev_fym 
        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 T1."COUNTRY" IN ('ENGLAND', 'France')
        AND T3."FISCALYEAR" IN ('2014','2015','2016')
    )
    WHERE "FISCALYEAR" IN ('2016')
    GROUP BY
    "REGION"
    , "COUNTRY"
    , "IDNum"
    , "CUSTOMER"
    , "BUSSINESS"
    , "FISCALYEARMONTH"
    , "FISCALYEAR"
    ;
    


    1. OraclePLSQLの例の表タイプ

    2. ORA-01722:番号が無効です。特定の行を検索してください

    3. この単純なSQLクエリを解決できますか?

    4. sql jdbc getgeneratedkeysは、列IDが見つからない、列タイプが不明であることを返します