使用sql sum函数得到错误的结果

时间:2014-09-16 02:27:15

标签: mysql sql sql-server

select 
    c.c_name, 
    sum(s.net_amount) - sum(cp.recived_amount) as amount 
from customer_payments cp
inner join customer c 
    on c.c_id = cp.customer_id 
inner join sale s 
    on s.cId = c.cId 
group by 
    c.c_name 
having 
    sum(cp.net_amount) - sum(recived_amount) !=0

我有3张桌子:

Customer(cId)(cName)
Sale(cId)(net_amount)
Customer_payment(cId)(received_amount)

我想将net_amount和received_amount相加并减去它们。 通过内部连接,我将两行相加,但它没有给出正确的结果。

1 个答案:

答案 0 :(得分:1)

一个问题是您正在为每位客户购买笛卡尔积。另一个是当没有匹配时你可能会丢失行。

您可以使用left join并预先汇总值来解决这些问题:

select c.c_name, sum(s.net_amount) - sum(cp.received_amount) as amount
from customer c left join
     (select cp.customer_id, sum(cp.received_amount) as receivedamount
      from customer_payments cp
      group by cp.customer_id
     ) cp 
     on c.c_id = cp.customer_id left join
     (select s.cId, sum(s.net_amount) as net_amount
      from sale s
      group by s.cId
     ) s
     on s.cId = c.cId
group by c.c_name
having sum(cp.net_amount)-sum(received_amount) <> 0;

除非给定的客户具有多个同名的ID,否则不需要外部聚合。