I have following table
no status amount
1 2 10000
2 3 10000
3 2 1000
4 2 -11000
I got running some by using following query.
SELECT
main.no
, main.status
, main.amount
, SUM(main.amount) OVER (
ORDER BY
main.no ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
from
table AS main
It returned follows. But I would like to improve my formula by refering to status
code.
no status amount running_sum
1 2 10000 10000
2 3 10000 20000
3 2 1000 21000
4 2 -11000 10000
My desired result is following.
I would like to get running sum only in status = 2
after another status code.
no status amount running_sum
1 2 10000 10000
2 3 10000 20000
3 2 1000 11000
4 2 -11000 0
How to add conditioning in my formula ?
Are there any good way to achieve this?
Thanks
2
Answers
You can do it using
sum(amount) over(partition by status order by no)
Demo here
According to your expected output, when
status = 2
, you just need to subtract the running sum of the amount wherestatus <> 2
from your running sum, try the following:Demo