SQL:如何选择总计为某个值的行


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

我想选择总计为某个值的行。

我的SQL(SQL Fiddle):

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

它应该计算总计410000并获得行。同时,它应该得到这样的东西:

id  user_id     storage
2   1           42552
3   1           367225

如您所见,42552+367225=409777。它选择了近410000的两行。

我什么都试过了,但都没用:(

对不起我的语言,我是德国人。

您可以使用相关的子查询来获取运行总数,并检索那些运行总数为<指定的数字。(注意,我将存储列更改为int。如果它是varchar,则比较将返回错误的结果)

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

编辑:当存储列中存在重复值时,必须通过包含id列的条件来在运行总和中对其进行说明。(在这种情况下,使用了<条件,因此会拾取重复存储值的最小id)

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

这就是您所需要的:

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

我添加了"ORDERBY存储ASC"来跳过那些需要大量存储的行。