Reputation: 239
Below is the actual invoice table
After grouping it based on invoiceID, the resultset is
And actual payment table is
and its payment resultset after grouping based on invoiceID is
Now i want to join these two resultsets [Payment and Invoice table] and find the balance amount subtracting Total from Amount based on InvoiceID and for non matching records the balance column should be zero. I tried this, but didn't get the expected result.
Upvotes: 1
Views: 324
Reputation: 263853
Try something like this,
SELECT a.InvoiceID,
a.totalSum InvoiceAmount,
b.totalSum PaymentAmount,
a.totalSum - COALESCE(b.totalSum, 0) TotalBalance
FROM
(
SELECT InvoiceID, SUM(Total) totalSum
FROM InvoiceTB
GROUP BY InvoiceID
) a LEFT JOIN
(
SELECT InvoiceID, SUM(Total) totalSum
FROM paymentTB
GROUP BY InvoiceID
) b
ON a.InvoiceID = b.InvoiceID
Upvotes: 1