I have a table with id,date and amount, i need to get the list,of id's, ordered by date DESC, that in total to be greater or equal than some specific value.
id | date | amount
----|----------|--------
1 | 1/1/2017 | 3
2 | 2/1/2017 | 5
3 | 3/1/2017 | 4
4 | 4/1/2017 | 2
5 | 5/1/2017 | 7
6 | 6/1/2017 | 4
For example
There is a very similar question and solution Postgresql select until certain total amount is reached but I need a bit different.
Thanks for any help.
Just use a cumulative sum:
select t.*
from (select t.*, sum(amount) over (order by date desc) as running_amount
from t
) t
where running_amount - amount < 12
order by date desc;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With