多个mysql表列的求和、减法和联接

vwhgwdsa  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(547)

我有四张mysql表 client , transaction , other_loan 以及 payment . 我想得到 sumload_amount 以及 additional 从表 transaction + sumamountother_loan 以及 subtract 把它送到 sumpayment_amount 在表中 payment . 我怎样才能做到呢?
我想要的结果:

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

我的表:事务

>  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

表:其他贷款

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

表:付款

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

表:客户

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

nzk0hqpo1#

因为你有多个交易,其他贷款金额和支付每个客户,你不能做一个直接的交易 JOIN 因为这会导致行的复制,从而导致不正确的值。相反,我们 SUM 在执行 JOIN . 另外,由于有些客户机在每个表中没有条目,因此必须使用 LEFT JOIN s和 COALESCE 这样空行就不会导致和变为 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

sqlfiddle演示

相关问题