查询仅返回基于金额的行数

时间:2013-08-27 20:00:49

标签: mysql sql database

我有一张应付款的下表

enter image description here

情景:

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:

  1. 检查余额是否大于0
  2. 仅返回付款适用的行。 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.
  3. 我想要一个只返回付款适用行数的查询?

    更新我!

1 个答案:

答案 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

SQL Fiddle

中的上述查询

一些注意事项:

  • 由于duedate不是唯一的,我添加了payableid(我假设 唯一)。 为了保持一致性,ORDER BY 的子查询中的p必须是唯一的。
  • 子查询返回的结果必须仅包含可以记入金额的记录。
    (因此,如果您有account_id列或其他类似列,则将其包含在子查询中的WHERE中。
  • 子查询返回的结果尽可能小,以便最佳选择 (因此我们在子查询中放置WHERE balance > 0,在外部查询中放置 not
  • 如果您想知道“为什么子查询?”:因为{<1}}在选择之后执行。 因此,如果我们不使用子查询,ORDER BY将被错误地应用,@left将变得无用。