如何从表中选择,直到总数是一个特定的数字?

时间:2012-01-13 07:22:00

标签: mysql sql

我有一张这样的桌子:

"ID"   "oamount"
'1'     '1500'
'2'     '2000'
'3'     '2000'
'4'     '1000'

并且有3000的买单 所以我需要选择像这样的查询“

"ID"   "oamount"   "request"
'1'     '1500'       '1500'
'2'     '2000'       '1500'

如果订单金额是4000那么

"ID"   "oamount"   "request"
'1'     '1500'       '1500'
'2'     '2000'       '2000'
'3'     '2000'       '500'

所以我需要选择所有行,直到金额完成,但最后一行将代表金额的其余部分。

2 个答案:

答案 0 :(得分:3)

您可以通过添加额外的列来更轻松地自己,其中包含ID较低的金额总和。

"ID" "oamount" "mamount"
'1'  '1500'    '0'
'2'  '2000'    '1500'
'3'  '2000'    '3500'
'4'  '1000'    '5500'

然后,您可以根据新列进行选择:

SELECT `ID`,
    CASE WHEN `oamount` < @Amount - `mamount`
         THEN `oamount`
         ELSE @Amount - `mamount` END AS `amount`
FROM `yourtable`
WHERE `mamount` < @Amount

可以这样做而不添加这个额外的列,但你会不必要地做一些事情。

答案 1 :(得分:3)

尝试此查询 -

SET @req = 4000;
SET @sum = 0;
SELECT id, oamount, IF(s > @req, oamount - (s - @req), oamount) request FROM (
  SELECT id, oamount, @sum := @sum + oamount s FROM amounts ORDER BY id) t
WHERE s - oamount < @req;

+------+---------+---------+
| id   | oamount | request |
+------+---------+---------+
|    1 |    1500 |    1500 |
|    2 |    2000 |    2000 |
|    3 |    2000 |     500 |
+------+---------+---------+