Home Forums Programming General SQL Query to subtract credit from Invoice Total RE: SQL Query to subtract credit from Invoice Total

  • Should be straightforward from here, Bill:

    DROP TABLE #Invoices

    CREATE TABLE #Invoices (InvoiceNo VARCHAR(10), Amount DECIMAL(10,2))

    INSERT INTO #Invoices (InvoiceNo, Amount)

    SELECT '1001', $230.00 UNION ALL --

    SELECT '1002', $135.56 UNION ALL --

    SELECT '1003', $201.00 UNION ALL -- * Does not need to show on report

    SELECT '1003CM', $201.00 UNION ALL -- * Does not need to show on report

    SELECT '1004', $134.00 UNION ALL -- * Report needs to show $135 - $35 = $100 <- show total

    SELECT '1004CM', $65.00 -- * Does not need to show on report

    SELECT *

    FROM #Invoices i

    CROSS APPLY (

    SELECT Credits = SUM(Amount)

    FROM #Invoices c

    WHERE c.InvoiceNo = i.InvoiceNo+'CM'

    ) c

    WHERE RIGHT(InvoiceNo, 2) <> 'CM'

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden