我有一张应付款的下表
情景:
We are going to pay 6000 to our vendor, this payment apply on 2nd row and remaining 2500 apply on 3rd row. after apply the 2500 on 3rd row , there will be a remaining balance of 1000.
Now I want to write a query that return number of rows base on payment enter. The conditions of query are as follow:
i.e. In above scenario, payment was 6000, and then query check that in which 6000 apply, base upon that decision it should return rows. In 6000 case he should return 2nd and 3rd row, if payment = 8000 then query will return 3 row because 7000 satisfy/ clear 2nd & 3rd payable and remaining 1000 will reduce the balance of 4th entry.
我想要一个只返回付款适用行数的查询?
更新我!
答案 0 :(得分:3)
考虑到duedate
订购的请求,并知道“剩下”多少,您会得到如下内容。此查询将为您提供left
中付款剩余的金额以及new_balance
中付款后的余额(剩余部分)。
SELECT p.*,
IF(balance < @left, 0, balance - @left) AS 'new_balance',
@left := IF(balance > @left, 0, @left - balance) AS 'left'
FROM (
SELECT * FROM payable
WHERE balance > 0
ORDER BY duedate, payableid
) AS p
JOIN (SELECT @left := 6000) AS r ON @left > 0
中的上述查询
一些注意事项:
duedate
不是唯一的,我添加了payableid
(我假设 唯一)。
为了保持一致性,ORDER BY
的子查询中的p
必须是唯一的。account_id
列或其他类似列,则将其包含在子查询中的WHERE
中。WHERE balance > 0
,在外部查询中放置 not 。ORDER BY
将被错误地应用,@left
将变得无用。