2

私は支払いのための次の表を持っています

ここに画像の説明を入力

シナリオ:

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.

支払いが適用される行数のみを返すクエリが必要ですか?

私を更新してください!

4

1 に答える 1

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サブクエリに配置します)。
  • 「なぜサブクエリを使用するのですか?」と疑問に思われる場合は、選択後にORDER BY実行されるためです。そのため、サブクエリを使用しない場合、誤って適用され、役に立たなくなります。@leftORDER BY
于 2013-08-27T20:10:01.903 に答える