Like in below if my target_sum is
- 5 it should return id 1
- 8 then it should return id 1 and 2
- 13 then it should return id 1, 2 and 3
Basically my query should return the next possible sum above my target_sum how to modify below query
id | marks |
---|---|
1 | 5 |
2 | 7 |
3 | 6 |
4 | 9 |
SELECT *
FROM (
SELECT *,
SUM(marks) OVER (ORDER BY id) AS cum_sum
FROM students
) t
WHERE cum_sum <= target_sum
ORDER BY id
2
Answers
Add one to the
cum_sum
and useLAG
to pass it in the next rowData
Query
This statement does the trick.
It uses the
lag
function to access thesum
of the previous row.DB fiddle to play with the query.