I have a table like this:
id | date | capacity | depot | reserved | order_id |
---|---|---|---|---|---|
1 | 2024-04-29 | 69 | 1 | 0 | 0 |
2 | 2024-04-29 | 49 | 1 | 0 | 0 |
3 | 2024-04-29 | 69 | 1 | 0 | 0 |
4 | 2024-04-29 | 69 | 1 | 0 | 0 |
Now I want to get only row where the sum of "capacity" is nearly to 100 – so my output should be
id | date | capacity | depot | reserved | order_id |
---|---|---|---|---|---|
1 | 2024-04-29 | 69 | 1 | 0 | 0 |
2 | 2024-04-29 | 49 | 1 | 0 | 0 |
Could you help me find the correct SQL statement?
I tried already to sum the capacity and group it by id with having sum >= 100 but I still get no results
2
Answers
See the linked fiddle, but I was able to get results for the test data you provided with the following:
Here I’m assuming you want to sum by date, but if that’s not the case you should be able to swap out the aggregation column easily:
fiddle
A sample.
Caution! Do not reproduce on large datasets, this may hang your database server!
The solution. In practice we need the closest combination only, so LIMIT 1 should be added to the query. I have not added it, but the rows numbering is added instead. This allows you to understand the amount of investigated combinations and, hence, the size of temporary buffer needed.
fiddle