I have 2 database tables. One that tracks placements of orders made to a company, and the other that tracks payments made to the company for orders.
I'd like to create an SQL query, that displays each order ID, the total amount for the order, and the amount outstanding for the order, which is yet to be paid. Customers are allowed to pay in 'instalments' say, So the purpose is to calculate the total outstanding and display it.
here is what i have so far, however it is returning 'null' when no payments have been made. This obviously means that there are no records based on a specific order, and so the total amount paid by the customer = 0. Therefore the amount outstanding is equal to the total amount.
I would like my sql code to display the total amount of the order when the entire amount is still outstanding, instead of the null.
How can this be done?
I tried a case statement but I think my syntax is wrong.
Here's the version without the case statement, which returns null when no payments have been made:
SELECT
pb_orders.id AS 'Order ID', pb_orders.order_total AS 'Total',
SUM(pb_payments.amount) AS 'Amount Paid', pb_orders.order_total -
SUM(pb_payments.amount) AS 'Outstanding Amount'
FROM
pb_orders
INNER JOIN
pb_payments ON pb_orders.id = pb_payments.link_id
WHERE
pb_orders.id = 1556
And here is my attempt at the case statement:
SELECT
pb_orders.id AS 'Order ID', pb_orders.order_total AS 'Total',
SUM(pb_payments.amount) AS 'Amount Paid'
WHEN 'Amount Paid' = 'NULL'
THEN 'Amount Paid' = pb_orders.order_total,
pb_orders.order_total - SUM(pb_payments.amount) AS 'Outstanding Amount',
FROM
pb_orders
INNER JOIN
pb_payments ON pb_orders.id = pb_payments.link_id
WHERE
pb_orders.id = 1555
CASE, but I don't seeCASEanywhereWHENandTHENbut you haven't includedCASEandEND)