I have a table that looks like this
id remaining expiry_date
1 200 2019-11-15
2 10 2019-11-23
3 10 2019-11-16
4 10 2019-11-16
5 7 2019-11-16
I want to fetch the results that have a running total of 215 that is sorted by expiry_date
in ascending
order.
What I am able to achieve so far?
SELECT *, @sum := (@sum + remaining) AS csum
FROM tickets
JOIN (SELECT @sum := 0) r
WHERE @sum < 215
ORDER BY id;
This query returns the following result which is correct.
id remaining expiry_date csum
1 200 2019-11-15 200
2 10 2019-11-23 210
3 10 2019-11-16 220
But when I try to sort it with expiry_date
it returns all the records.
SELECT *, @sum := (@sum + remaining) AS csum
FROM tickets
JOIN (SELECT @sum := 0) r
WHERE @sum < 215
ORDER BY expiry_date;
Result:
id remaining expiry_date csum
1 200 2019-11-15 200
3 10 2019-11-16 210
4 10 2019-11-16 220
5 7 2019-11-16 227
2 10 2019-11-23 237
The sorting is correct but the result is way more than I need.
What I want
I want to return the following result.
id remaining expiry_date csum
1 200 2019-11-15 200
3 10 2019-11-16 210
4 10 2019-11-16 220
Also, the number 215 can change dynamically so the number of rows returned can vary based on that number. How can I change the query so I can achieve this?
Edit
I apologize for not being clear with what I actually wanted in my result set. Please let me clarify with this edit. I don't want the records with running-total less than the given amount. I want the records until the running-total is equal to or exceeds the given amount.