我正在尝试将付款表中多个条目的付款金额相加,并显示买方是谁的订单
因此,如果两个人在一个订单上付款,它将显示他们的合并付款并显示付款人是谁。因此,如果Bob和Sue在30美元的账单上支付了10美元,那就会显示
Order Buyer Paid Owes
1 Bob 20 10
1 Sue 20 10
但我目前正在
Order Paid Owes
1 20 10
如何添加买家?可能加入? 目前我有。
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)
付款有一个buyerId和orderid作为外键,因为它是一个m到n的关系。
答案 0 :(得分:0)
正如您在评论中提及的那样,当您加入买家时,它并未向您提供所需的输出,即所有付款的总和。为了让买家和所有支付的总和加入支付表的另一个实例并使用它来计算总和将会起到作用。
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