I have two tables Orders and Payments with many-to-many relationship. Two different orders can be paid with one check and one order can be paid with several different checks. To link Orders table with Payments table I use third PaymentsOrders Table which has following layout:
PaymentsOrdersID – primary key
PaymentID – foreign key
OrderID – foreign key
I need help creating the query to show unpaid orders. I need to see difference between order amount and payment amount. I created following query which works fine if I have one order with multiple payments:
SELECT Orders.OrderID, Orders.OrderAmount, Sum(Payments.PaymentAmount) AS SumOfPayments, [OrderAmount]-[SumOfPayments] AS UnpaidAmount
FROM Payments INNER JOIN (Orders INNER JOIN PaymentsOrders ON Orders.OrderID = PaymentsOrders.OrderID) ON Payments.PaymentID = PaymentsOrders.PaymentID
GROUP BY Orders.OrderID, Orders.OrderAmount;
I run into problems when I have two different orders paid with one check. Query I created takes amount of the order and subtracts amount of the payment which is meant to cover two different orders and report will show this order as overpaid.
PaymentsOrdersID – primary key
PaymentID – foreign key
OrderID – foreign key
I need help creating the query to show unpaid orders. I need to see difference between order amount and payment amount. I created following query which works fine if I have one order with multiple payments:
SELECT Orders.OrderID, Orders.OrderAmount, Sum(Payments.PaymentAmount) AS SumOfPayments, [OrderAmount]-[SumOfPayments] AS UnpaidAmount
FROM Payments INNER JOIN (Orders INNER JOIN PaymentsOrders ON Orders.OrderID = PaymentsOrders.OrderID) ON Payments.PaymentID = PaymentsOrders.PaymentID
GROUP BY Orders.OrderID, Orders.OrderAmount;
I run into problems when I have two different orders paid with one check. Query I created takes amount of the order and subtracts amount of the payment which is meant to cover two different orders and report will show this order as overpaid.