【问题标题】:SQL: How to select rows that sum up to certain valueSQL:如何选择总和为某个值的行
【发布时间】:2023-03-08 19:58:01
【问题描述】:

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

我的 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 的两行。

我已经尝试了所有方法,但没有成功:(

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

【问题讨论】:

  • 使用 php 将是微不足道的你想要一个 mysql 唯一的解决方案?
  • 您似乎对 StackOverflow 比较陌生。如果答案对您有所帮助,请务必投票。如果它解决了您的问题,请将答案标记为已接受。
  • @GeorgePant 不,PHP 会更好:)
  • 这看起来可以通过动态规划或回溯更好地解决。
  • I have tried everything but it didn't work :( 我不确定,真的一切吗?应该相信这一点吗? :D 没关系,请看看mattgemmell.com/what-have-you-tried。与其说出来,不如说每个人都应该展示(代码)已经尝试过的内容

标签: php mysql sql sum


【解决方案1】:

这是你需要的:

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

我添加了“ORDER BY storage ASC”来跳过需要大量存储的行。

【讨论】:

    【解决方案2】:

    您可以使用相关子查询来获取运行总计并检索运行总计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 列的条件将其计入运行总和。 (在这种情况下,&lt; 条件已被使用,因此重复存储值的最小 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
    

    【讨论】:

    • 当它们具有相同的值时,您只需选择其中的一行。在这种情况下,在 user_id 和存储上使用 group by。但是,这在其他情况下也是一个问题。我会解决它。
    • 查看不需要group by的编辑版本。
    猜你喜欢
    • 1970-01-01
    • 2012-03-20
    • 1970-01-01
    • 2011-08-08
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    相关资源
    最近更新 更多