多个mysql表列的总和,减和联接

时间:2018-12-11 06:31:19

标签: mysql join sum subtraction

我有四个mysql表clienttransactionother_loanpayment。我想从sum和{{中获取表load_amount的{​​{1}}和additional到表transaction的{​​{1}}和sum的{​​{1}} 1}}到表amountother_loan的{​​{1}}中。我该如何实现?

  

我想要的结果:

subtract
  

我的桌子:   交易

sum
  

表:other_loan

payment_amount
  

表格:付款

payment
  

表:客户

>  ID | Name     |  Amount
>  1  | Robin    | 8718  
>  2  | Reynaldo | 21
>  3  | Leomar   | 0

1 个答案:

答案 0 :(得分:1)

由于您有多个交易,其他每个客户的贷款额和还款额,因此您无法对表进行直接JOIN的交互操作,因为这将导致行的复制,从而导致错误的值。取而代之的是,我们在做SUM之前,先在客户基础上JOIN在客户端基础上每个表中的所有值。另外,由于某些客户端在每个表中都没有条目,因此您必须在结果上使用LEFT JOINCOALESCE,以便空行不会导致SUM变为NULL。此查询应为您提供所需的结果:

SELECT c.id, c.name,
       COALESCE(t.transactions, 0) + COALESCE(o.amounts, 0) - COALESCE(p.payments, 0) AS amount
FROM client c
LEFT JOIN (SELECT id, SUM(load_amount) + SUM(additional) AS transactions
           FROM transaction
           GROUP BY id) t on t.id = c.id
LEFT JOIN (SELECT id, SUM(amount) AS amounts
           FROM other_loan
           GROUP BY id) o ON o.id = c.id
LEFT JOIN (SELECT id, SUM(payment_amount) AS payments
           FROM payment
           GROUP BY id) p ON p.id = c.id
GROUP BY c.id

输出(用于您的示例数据):

id  name        amount
1   Robin       8718
2   Cinderella  21
3   Leomar      0

Demo on SQLFiddle