SQL: How to select rows that sum up to certain value

寵の児 提交于 2021-02-19 03:43:07

问题


I want to select rows that sum up to a certain value.

My SQL (SQL Fiddle):

id  user_id     storage
1   1           1983349
2   1           42552
3   1           367225
4   1           1357899
37  1           9314493

It should calculate the sum up to 410000 and get the rows. Meanwhile it should get something like this:

id  user_id     storage
2   1           42552
3   1           367225

As you can see, 42552 + 367225 = 409777. It selected two rows that are nearly 410000.

I have tried everything but it didn't work :(

Sorry for my language, I am German.


回答1:


You can use a correlated subquery to get the running total and retrieve those rows whose running total is < a specified number. (note that i changed the storage column to int. if it is a varchar the comparison would return the wrong result)

select id,user_id,storage
from uploads t
where storage+coalesce((select sum(storage) from uploads 
                        where storage<t.storage),0) < 410000
order by storage

SQL Fiddle

Edit: When there are duplicate values in the storage column, it has to be accounted for in the running sum by including a condition for the id column. (in this case < condition has been used, so the smallest id for a duplicate storage value gets picked up)

select id,user_id,storage
from uploads t
where storage+coalesce((select sum(storage) from uploads 
                        where storage<t.storage 
                        or (storage=t.storage and id < t.id)),0) < 410000
order by storage



回答2:


This is what you need:

SET @suma = 0;
SELECT @suma:=@suma+`storage`, id, storage FROM table 
WHERE @suma<=410000 
ORDER BY storage ASC;

I added "ORDER BY storage ASC" to skip rows that have to much storage.



来源:https://stackoverflow.com/questions/38663219/sql-how-to-select-rows-that-sum-up-to-certain-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!