簡體   English   中英

查詢父表時如何獲取子表列的SUM?

[英]How to get SUM of a column of a child table when query parent table?

我有兩張桌子

賬戶表(賬戶)

id      name
1       Account 1
2       Account 2
3       Account 3
4       Account 2

交易表(交易)

id      account_id     type      amount     datetime
1       1              credit    500        2020-04-01 06:00:00
2       1              credit    300        2020-04-01 06:00:00
3       2              credit    100        2020-04-01 06:00:00
4       2              debit     50         2020-04-01 06:00:00
5       1              debit     600        2020-04-01 06:00:00
6       3              credit    1000       2020-04-01 06:00:00
7       1              credit    100        

我的目標是在一個查詢中獲取帳戶id, name, balance 余額將從交易表中計算SUM of Credit Amount - SUM of Debit Amount總和SUM of Credit Amount - SUM of Debit Amount給定帳戶SUM of Credit Amount - SUM of Debit Amount總和。

目標輸出

   id      name          balance
   1       Account 1     300
   2       Account 2     50
   3       Account 3     1000
   4       Account 4     0

可能的查詢

SELECT id, name, ((SELECT SUM(amount) FROM transaction WHERE type = 'credit' AND account_id = {ACCOUNT_ID} ) - (SELECT SUM(amount) FROM transaction WHERE type = 'debit' AND account_id = {ACCOUNT_ID} )) as balance

是否可以在一個查詢中執行此操作,如果是,如何執行此操作。

您可以在派生表中進行聚合,以避免必須按頂級中的許多字段進行分組的問題。 例如:

SELECT a.id, a.name, COALESCE(b.balance, 0) AS balance
FROM account a
LEFT JOIN (
  SELECT account_id,
         SUM(CASE WHEN type='credit' THEN amount ELSE 0 END) -
         SUM(CASE WHEN type='debit' THEN amount ELSE 0 END) AS balance
  FROM transaction
  GROUP BY account_id
) b ON b.account_id = a.id

輸出:

id  name        balance
1   Account 1   300
2   Account 2   50
3   Account 3   1000
4   Account 2   0

SQLFiddle 上的演示

您需要將account left jointransaction以便您可以按每個帳戶分組並根據type有條件地總結amount

select 
  a.id, a.name,
  sum(case when type = 'credit' then 1 else -1 end * coalesce(t.amount, 0)) balance
from account a left join transaction t
on t.account_id = a.id
group by a.id, a.name

暫無
暫無

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

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