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

ev7lccsx  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(292)

我有一张这样的table:

+----+--------+
| id | amount |
+----+--------+
|  1 |     20 |
|  2 |     30 |
|  3 |     10 |
|  4 |     50 |
|  5 |      5 |
+----+--------+

如果我有价值的话 set @amount = 75; 我想得到最大的 amount 这就足够了。所以在这种情况下 id s:会的 4,2 即使这意味着 80 .
伪代码:
pop集合中的最大值<= @amount 把身份证放进去 arr 如果总和< @amount 转到步骤1。
打印 arr

roejwanj

roejwanj1#

您可以使用累积和:

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;
g52tjvyc

g52tjvyc2#

我不确定您的用例,可能可以通过以下方式完成:

SELECT 
 GROUP_CONCAT(id SEPARATOR ',') AS ids
 SUM(t.amount)
FROM (
   SELECT 
    id as id,
    'group' as group,
    amount as amount
   FROM you_table
   WHERE amount <= @amount
   ORDER BY amount DESC
   LIMIT 2) as t
GROUP BY t.group

否则需要在存储过程中使用游标:

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;

代码没有被检查过,很简单。希望这能有所帮助。

相关问题