Using multiple JOINS. SUM() producing wrong value

前端 未结 2 1964
野趣味
野趣味 2020-12-15 11:28

I am getting some basic invoice information in a SQL query and figuring the Order Total and Payment Totals in the same query. Here is what I have thus far:

S         


        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 12:14

    If you run the query without a group by, you'll see that some payments have multiple rows. That's because you're also joining on order items. The result set will contain a row for each combination of orderitem and payment.

    One solution would be to change the sum to:

    ,        
    ,    (   select SUM(payments.amount) 
             from payments 
             where payments.orderID = orders.id
         ) AS totalPayments
    ,    
    

    This would ensure the payments with multiple orderitems are not summed multiple times.

提交回复
热议问题