![](/img/trans.png)
[英]Mysql Query select where the sum from one table is compared to the sum of rows in another table
[英]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 by
並having
:
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.