我有一個看起來像這樣的表:
| 翻譯日期 | tran_num | tran_type | tran_status | 數量 |
|---|---|---|---|---|
| 2021 年 2 月 12 日 | 74 | SG | ? | 1461 |
| 2021 年 9 月 1 日 | 357 | SG4 | ? | 2058 |
| 2021 年 10 月 27 日 | 46 | SG4 | 是 | -2058 |
| 2021 年 10 月 27 日 | 47 | SG | ? | 2058 |
如果按 tran_date 和 tran_num 排序,我想識別具有負數的行并將前一行的總和為 0。
預期輸出:
| 翻譯日期 | tran_num | tran_type | tran_status | 數量 |
|---|---|---|---|---|
| 2021 年 2 月 12 日 | 74 | SG | ? | 1461 |
| 2021 年 10 月 27 日 | 46 | SG4 | 是 | 0 |
| 2021 年 10 月 27 日 | 47 | SG | ? | 2058 |
uj5u.com熱心網友回復:
您可以嘗試在子查詢中使用滯后函式,然后像這樣計算數量:
select x.tran_date,x.tran_num, x.tran_type, x.tran_status,
case
when x.amount<0 then x.amount x.lag_win
else x.amount
end amount
from
(
select tt.*,
lag(amount,1) over (order by tran_date,tran_num) lag_win,
abs(tt.amount) lead (amount,1,1) over (order by tran_date,tran_num) pseudo_col
from tran_table tt
)x
where pseudo_col!=0
結果:
12.02.2021 74 SG N 1461
27.10.2021 46 SG4 Y 0
27.10.2021 47 SG N 2058
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466326.html
