答案 0 :(得分:1)
您可以使用变量来获取感兴趣的行以及更新记录所需的信息:
SELECT *
FROM (
SELECT `Qty in acquisto`,
`Prezzo in acquisto`,
@take := least(`Qty in acquisto`, @needed) as taken,
`Qty in acquisto` - @take as adjusted_acquisto,
@needed := @needed - @take as still_needed
FROM book,
(select @needed := 5) as init
ORDER BY `Prezzo in acquisto` DESC) base
WHERE taken + still_needed > 0
样本数据的输出是:
| Qty in acquisto | Prezzo in acquisto | taken | adjusted_acquisto | still_needed |
|-----------------|--------------------|-------|-------------------|--------------|
| 2 | 1000 | 2 | 0 | 3 |
| 10 | 960 | 3 | 7 | 0 |
请参阅SQL fiddle
在最里面的查询中,使用别名 init ,您可以传递所需的书籍数量(示例中为5)。
因此,在列adjusted_acquisto
中,您可以找到执行删除和更新所需的值:
如果该值为0,则删除相应的记录。
该值不为0,用该值更新数量。
答案 1 :(得分:1)
E.g:
SELECT * FROM my_table;
+------+--------+
| id | amount |
+------+--------+
| 800 | 8 |
| 900 | 3 |
| 950 | 4 |
| 960 | 10 |
| 1000 | 2 |
+------+--------+
SELECT n.id
, GREATEST(amount-@x,0) new_amount
, @x:=GREATEST(@x-amount,0) x
FROM my_table n
, (SELECT @x:=5) vars
ORDER
BY id DESC;
+------+--------+------------+------+
| id | amount | new_amount | x |
+------+--------+------------+------+
| 1000 | 2 | 0 | 3 |
| 960 | 10 | 7 | 0 |
| 950 | 4 | 4 | 0 |
| 900 | 3 | 3 | 0 |
| 800 | 8 | 8 | 0 |
+------+--------+------------+------+