Here is one way. There are probably better ways, but I had a spare minute... :)-- Set up sample dataCREATE TABLE #PartyInvoice (PartyID CHAR(1), InvoiceNumber VARCHAR(50), Amount MONEY)INSERT #PartyInvoiceSELECT 'A', 'Invoice001', $100UNION ALL SELECT 'A', 'Invoice002', $200UNION ALL SELECT 'A', 'Invoice003', $400UNION ALL SELECT 'B', 'Invoice003', $250 CREATE TABLE #PartyPayment (PartyID CHAR(1), PaymentNumber VARCHAR(50), Amount MONEY)INSERT #PartyPaymentSELECT 'A', 'Pay001', 150UNION ALL SELECT 'B', 'Pay002', 50-- Creae CTE;WITH Invoice (PartyID, InvoiceNumber, InvoiceAmount, PaymentAmount)AS( SELECT PartyID, InvoiceNumber, Amount AS InvoiceAmount, Payment.PaymentAmount FROM #PartyInvoice AS Invoice CROSS APPLY ( SELECT SUM(Amount) AS PaymentAmount FROM #PartyPayment AS Payment WHERE Payment.PartyID = Invoice.PartyID ) AS Payment)-- Perform SelectSELECT A.PartyID, A.InvoiceNumber, A.InvoiceAmount, CASE WHEN SUM(B.InvoiceAmount) - A.PaymentAmount < 0 THEN 0 ELSE SUM(B.InvoiceAmount) - A.PaymentAmount END AS PendingAmountFROM Invoice AS ALEFT OUTER JOIN Invoice AS B ON A.PartyID = B.PartyID AND A.InvoiceNumber >= B.InvoiceNumberGROUP BY A.PartyID, A.InvoiceNumber, A.InvoiceAmount, A.PaymentAmountORDER BY A.PartyID, A.InvoiceNumber-- CleanupDROP TABLE #PartyInvoiceDROP TABLE #PartyPayment