我有一张这样的表:
CREATE TABLE `PQ_batch` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Batch Id number',
`date` datetime DEFAULT NULL,
`qty` int(11) DEFAULT NULL COMMENT 'Number of units in a batch',
PRIMARY KEY (`bid`)
) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
Id | date | qty
--------------------------------
1 2017-01-06 5
2 2017-01-02 5
3 2017-01-03 100
给定的数值: @qtyToTake:= 100
*选择满足@qtyToTake所需的行,并且仅选择这些行,从每行获取的数量以及该行剩余的新数量。最早的批次应该先用完。 *
看起来应该是这样的:
Id | date | qty | newQty | qtyTakenPerRecord
-------------------------------------------------------
1 2017-01-02 5 0 5
2 2017-01-03 100 5 95
3 2017-01-01 5 5 0
newQty =(qty - @qtyToTake)其中@qtyToTake =(@qtyToTake - 前一行' s数量,直到@qtyToTake达到0)
@qtyToTake应动态分配为前一行的数量及其当前值的差值,直到达到0.
这是我想出的:
SELECT p.bid, p.Orig as origQty, p.NewQty, (p.Orig - p.NewQty) AS NumToTake
FROM(
SELECT b.bid, (@runtot := b.bqty - @runtot) AS remain, ( @runtot := (b.bqty - @runtot) ) leftToGet, b.bqty AS Orig,
(SELECT
(sum(bqty) - @runtot) AS tot FROM PQ_batch
WHERE bid <= b.bid ) AS RunningTotal,
(SELECT
CASE
WHEN (sum(bqty) - @runtot) > 1 THEN (sum(bqty) - @runtot)
ELSE 0
END
FROM PQ_batch
WHERE bid <= b.bid ) AS NewQty
FROM PQ_batch b,(SELECT @runtot:= 100) c
ORDER BY bdate
) AS p
答案 0 :(得分:0)
在这里使用@McNets示例&#39; s我想出的:
SELECT bid, bdate,bpid,bcost, bqty, newQty, qtyTakenPerRecord
FROM (
SELECT y.*,
IF(@qtyToTake > 0, 1, 0) AS used,
IF(@qtyToTake > bqty, 0, bqty - @qtyToTake) AS newQty,
IF(@qtyToTake > bqty, bqty, bqty - (bqty - @qtyToTake)) AS qtyTakenPerRecord,
@qtyToTake := @qtyToTake - bqty AS qtyToTake
FROM
(SELECT @qtyToTake := 100) x,
(SELECT * from PQ_batch WHERE bpid =1002 AND bqty > 0 ORDER BY bdate) y
) z
WHERE used = 1
ORDER BY bdate