Using multiple JOINS. SUM() producing wrong value

前端 未结 2 1957
野趣味
野趣味 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:12

    my guess is that the payment is $10 and there are two items in the order (orderitems table). if that's the case, try using a GROUP BY on the orders/customers/orderstatus fields.

    0 讨论(0)
  • 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:

    ,    <earlier columns>    
    ,    (   select SUM(payments.amount) 
             from payments 
             where payments.orderID = orders.id
         ) AS totalPayments
    ,    <later columns>
    

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

    0 讨论(0)
提交回复
热议问题