問題:領導團隊想查看每月采購的價值是增加還是減少。計算個人月與月的購買金額差異,以便每個月都有一個值代表該人與上個月的差異
我的代碼:
SELECT
person_id,
Month(transaction_date),
SUM(purchase_amount) - LAG(SUM(purchase_amount))
OVER (ORDER BY person_id, Month(transaction_date))
FROM transactions
GROUP BY person_id, Month(transaction_date)
ORDER BY person_id, Month(transaction_date);
此代碼似乎正在運行,但是輸出不正確。對于每個第一個唯一的患者 ID,總滯后量應該為空,但這不是我得到的。我需要使用磁區依據功能嗎?
uj5u.com熱心網友回復:
你主要回答了你自己的問題。您只需要order by person_id在視窗中替換為partition by person_id.
SELECT
person_id,
Month(transaction_date),
SUM(purchase_amount) - LAG(SUM(purchase_amount)) OVER (
partition by person_id
order by month(transaction_date)
)
FROM transactions
GROUP BY person_id, Month(transaction_date)
ORDER BY person_id, Month(transaction_date)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/460671.html
下一篇:使用PHP從URL解碼資料
