求和并正确加入该列

sum and join the column correctly

数据库

贷款

[id_loan] [id_customer] [qty_loan][amount] 
  1            1             2       8 
  2            1             1       4 
  3            2             3      12 
  4            1             1       4 

付款

[id_pay] [id_customer] [qty_pay] [pay]
  1            1           1       4 
  2            1           2       8 
  3            2           2       8 
  4            2           1       4 

我想加入然后得到总和结果但是结果是错误的这里是sql代码

SELECT
     SUM(qty_loan) as qty_loan,SUM(amount) as amount ,SUM(qty_pay) as qty_pay,SUM(pay) as pay  
    FROM loan JOIN payment ON loan.id_customer = payment.id_customer 
    WHERE loan.id_customer='1'

当我们在两个表中都有 2 条记录时,JOIN 找到 4 个匹配项并且每个值都是重复的。
我们可以查询sub-query中的一个表,按id_customer分组,来避免这个问题。

SELECT
  l.id_customer,
  qty_loan,
  amount ,
  SUM(qty_pay) as qty_pay,
  SUM(pay) as pay  
FROM (SELECT 
        id_customer,
        SUM(qty_loan) as qty_loan,
        SUM(amount) as amount 
        FROM loan 
        GROUP BY id_customer) l
LEFT JOIN payment 
ON l.id_customer = payment.id_customer 
/*-WHERE loan.id_customer='1'*/
GROUP BY 
  l.id_customer,  
  qty_loan,
  amount ;
id_customer | qty_loan | amount | qty_pay | pay
----------: | -------: | -----: | ------: | --:
          1 |        4 |     16 |       3 |  12
          2 |        3 |     12 |       3 |  12

db<>fiddle here