多个 mysql table 列的求和、减法和连接

Sum, Subtract and Join of multiple mysql table columns

我有四个 mysql tables clienttransactionother_loanpayment。我想从 load_amount sumadditional 从 table transaction + sumamountother_loansubtract 到 table paymentpayment_amountsum。我怎样才能实现它?

Result I want:

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

My Tables: transaction

>  tid | id| date       | load_amount | additional
>  1   | 1 | 2018-12-01 |    90       | 0  
>  2   | 1 | 2018-12-07 |    90       | 0
>  3   | 2 | 2018-12-08 |    49       | 2

table: other_loan

> oid | id| amount   |  date
> 1   | 1 | 7928     | 2018-12-10
> 2   | 1 | 750      | 2018-12-10

table: payment

> pid |id | payment_amount  | date
> 1   | 1 |      50         | 2015-12-10
> 2   | 1 |      90         | 2015-12-10
> 3   | 2 |      30         | 2015-12-10

table: client

> id | Name       |  
> 1  | Robin      | 
> 2  | Cinderella |
> 3  | Leomar     | 

因为您有多个交易、其他贷款金额和每个客户的付款,所以您不能直接对 table 进行 JOIN 操作,因为这会导致行复制,导致不正确的值。相反,在 执行 JOIN 之前,我们 SUM 基于客户端 每个 table 中的所有值。此外,由于某些客户端在每个 table 中没有条目,您必须在结果中使用 LEFT JOINs 和 COALESCE,这样空行就不会导致 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