简体   繁体   English

sql sum函数得到错误的结果

[英]getting wrong result with sql sum function

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

I have 3 tables: 我有3张桌子:

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

I want to sum net_amount and received_amount and subtract them both. 我想对net_amount和Received_amount求和,并减去它们两者。 Through inner join whem I am going to sum both rows it is not giving correct result. 通过内部连接,我将对两行求和,这不会给出正确的结果。

One problem is that you are getting a cartesian product product for each customer. 一个问题是您正在为每个客户获得笛卡尔产品。 Another is that you are possibly losing rows when there are no matches. 另一个是没有匹配项时,您可能会丢失行。

You can fix these problems by using left join and pre-aggregating the values: 您可以通过使用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;

The outer aggregation is not really needed, unless a given customer has multiple id for the same name. 除非是给定的客户具有相同名称的多个ID,否则实际上不需要外部聚合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM