Update previous days count using LAG function in ORACLE

北城以北 提交于 2021-02-10 20:23:00

问题


I have a table with columns as product, txn_date and no_of_txns. One more column prev_day_txn added recently to the column. Data is something like below:

Product   TXN_DATE  NO_OF_TXNS 

AA         1-JAN-19      100
AA         2-JAN-19      180
AA         3-JAN-19      290

With the new column added, data in the column should be populated with previous day's data. Output should be something like below:

Product       TXN_DATE     NO_OF_TXNS  PREV_DAY_TXN

    AA         1-JAN-19      100          0
    AA         2-JAN-19      180         100
    AA         3-JAN-19      290         180

I am trying to update the data using lag function, but getting error SQL Error: ORA-30483: window functions are not allowed hereSame query is working fine in select clause. This is what I tried:

update PRD_DTLS set PREV_DAY_TXN = LAG(NO_OF_TXNS, 1, 0) OVER (ORDER BY PRODUCT, TXN_DATE);

Can someone help me with the query. Thanks.


回答1:


You can use MERGE:

MERGE INTO PRD_DTLS A USING 
(
  SELECT
      PRODUCT,
      TXN_DATE,
      LAG(NO_OF_TXNS) OVER(
          PARTITION BY PRODUCT
          ORDER BY
              TXN_DATE
      ) AS PREV_TXN
  FROM
      PRD_DTLS 
)
B ON ( A.PRODUCT = B.PRODUCT
       AND A.TXN_DATE = B.TXN_DATE )
WHEN MATCHED THEN UPDATE SET A.PREV_DAY_TXN = CASE
    WHEN B.PREV_TXN IS NOT NULL THEN B.PREV_TXN
    ELSE 0
END;

Cheers!!




回答2:


One method uses a subquery:

UPDATE PRD_DTLS pd
    SET PREV_DAY_TXN = (SELECT COALESCE(MAX(NO_OF_TXNS) KEEP (DENSE_RANK FIRST ORDER BY TXN_DATE DESC), 0)
                        FROM PRD_DTLS pd2
                        WHERE pd2.PRODUCT = pd.PRODUCT AND
                              pd2.TXN_DATE < pd.TXN_DATE
                       );


来源:https://stackoverflow.com/questions/57661293/update-previous-days-count-using-lag-function-in-oracle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!