簡體   English   中英

基於行總和與另一個字段值比較的mySQL選擇

[英]mySQL select based on sum of rows compared to another field value

我有一張發票項目表。 一次交易可能會導致多個借項和多個貸項共享相同的invoice_set_id,如果sum(debits)> sum,我需要將借項的總和與貸項的總和進行比較,並將invoice_set_id添加到結果集中(學分)。 如果沒有帶有貸方金額的行,它也應該添加到結果中。 使用mySQL。 謝謝你的幫助。 示例表和結果如下:

invoice_item_id  invoice_set_id  credit_debit  amount
62                a22             debit         15.00
63                a22             debit          8.00
64                a22             credit        23.00
65                b23             debit         44.00
66                c55             debit         15.00
67                c55             debit          2.00
67                c55             credit         8.00

鑒於以上所述,結果集應為:

invoice_set_id
b23
c55

說明:由於借方和貸方相等,因此不返回a22,由於有借方但沒有貸方而返回b23,並且由於借方總和大於單個貸方而返回c55。

我對此表示感謝。 實際查詢涉及更多,但我認為這個特殊問題是我需要幫助的。

您可以簡單地使用group byhaving

select invoice_set_id
from t
group by invoice_set_id
having sum(case when credit_debit = 'debit' then amount else 0 end) > sum(case when credit_debit = 'credit' then amount else 0 end) ;

表達having子句的另一種方式是:

having sum(case when credit_debit = 'debit' then amount
                when credit_debit = 'credit' then - amount
                else 0
           end) > 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM