简体   繁体   中英

SQL Group by prevents summing across multiple records

I am trying to sum the amount paid across multiple entries in the Payment table and show who the buyers were for that Order

so if two people made payments on one order it would show their combined payments and show who the people who made the payment were. So if Bob and Sue made 10 dollar payments on a 30 dollar bill it would show

Order Buyer Paid Owes  
1     Bob   20   10
1     Sue   20   10

but i'm currently at

Order    Paid Owes  
1        20   10

How do I add in the buyers? possibly with a join? Currently I have.

Select Order.Orderid, sum(Payment.amount) as "Paid", Order.Price-sum(Payment.amount) as "Owes"
from order, payment
where payment.orderId = order.orderid 
group by (order.orderid, order.price)

payment has a buyerId and orderid as foreign keys since it is an m to n relation.

As you mention in your comment when you join the buyer it does not give you the desired output which is the sum of all payments. To get the buyers and the sum of all payments joining another instance of the payments table and using that to calculate the sum will do the trick.

SELECT
    Order.Orderid,
    Buyer.Name,
    SUM(PaymentSum.amount) AS 'Paid',
    Order.Price-SUM(PaymentSum.amount) AS 'Owes',
FROM
    Order
    JOIN Payment
        ON Order.Orderid = Payment.Orderid
    JOIN Buyer
        ON Payment.BuyerId Buyer.BuyerId
    JOIN Payment AS PaymentSum
        ON Order.Orderid = PaymentSum.Orderid
GROUP BY
    Order.Orderid,
    Order.Price,
    Buyer.Name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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