问题
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 here
Same 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