Mysql 返回sql查询中大于金额的金额的最小总和

Mysql 返回sql查询中大于金额的金额的最小总和,mysql,sql,Mysql,Sql,我有一张这样的桌子: +----+--------+ | id | amount | +----+--------+ | 1 | 20 | | 2 | 30 | | 3 | 10 | | 4 | 50 | | 5 | 5 | +----+--------+ 如果我有一个值,说set@amount=75;我想得到最大金额的ID来填充该金额。因此,在这种情况下,它将是ids:4,2,即使总数为80 伪代码: pop集合中的最大值您可以使用累积和:

我有一张这样的桌子:

+----+--------+
| id | amount |
+----+--------+
|  1 |     20 |
|  2 |     30 |
|  3 |     10 |
|  4 |     50 |
|  5 |      5 |
+----+--------+
如果我有一个值,说set@amount=75;我想得到最大金额的ID来填充该金额。因此,在这种情况下,它将是ids:4,2,即使总数为80

伪代码:


pop集合中的最大值您可以使用累积和:

select t.*
from (select t.*, sum(amount) over (order by amount desc, id) as running_amount
      from t
     ) t
where running_amount - amount < 75;
在MySQL 8.0之前的版本中,一种方法是关联子查询:

select t.*
from (select t.*,
             (select sum(t2.amount) from t t2 where t2.amount <= t.amount) as running_amount
      from t
     ) t
where running_amount - amount < 75;

我不确定您的用例,可能是这样的:

选择 组_CONCATid分隔符“,”作为ID 总额 从…起 选择 id作为id, "集团"作为集团,, 作为金额的金额 从你的桌子上
哈哈,我在努力!如果金额是45呢?或者54?45将是2,1,54将是4,2 psuedo代码没有帮助吗?我得到了语法错误:>MySQL服务器版本,以便使用接近“按金额订购”的正确语法,id为运行\u amount,从何处开始,我用自己的表或嵌套的表替换所有ts?我以前从未见过关键字over,我不确定它是否工作!嵌套查询select t.*,SUMMOUNT over order by amount desc,id as running\U amount from t在用my Table替换t时不起作用您使用的是什么版本的MySQL?限制为2是欺骗:很遗憾,不能使用存储过程!还有“团体”,因为团体似乎在投掷issues@maxisme“组”当然会像“组”一样抛出,因为“组”是一个保留的关键字,我没有想到这一点。但它应该像“组”一样工作`
DECLARE total;
DECLARE my_cursor CURSOR FOR SELECT id, amount FROM yourTable ORDER BY amount DESC;
DECLARE c_amount;
DECLARE c_id;
SET total = 0;
OPEN my_cursor;
counter_loop: WHILE total <= mount DO
  FETCH cursor_name INTO c_id, c_amount;
  set total = total + c_amount;
END counter_loop
CLOSE my_cursor;