Amy
Amy

Reputation: 523

SQL Query - Outstanding Payments

I have a query to retrieve outstanding payments from the database, which is the total invoice amount minus the total payment amount. The problem is though, when there are no payments against the invoice, these just don't show up. I want those invoice amounts to show up, with their total payment amount being zero. Here is my query:

SELECT DISTINCT Client.FirstName + ' ' + Client.LastName                   AS
                [Client Name],
                SUM(Invoices.InvoiceAmount)                                AS
                [Total Invoice Amounts],
                SUM(ClientPayments.PaymentAmount)                          AS
                [Total Amount Paid],
                SUM(Invoices.InvoiceAmount - ClientPayments.PaymentAmount) AS
                [Outstanding Payment Amount]
FROM   Invoices
       INNER JOIN ClientPayments
         ON Invoices.InvoiceNumberID = ClientPayments.InvoiceNumberID
       INNER JOIN Client
         ON Invoices.ClientNumberID = Client.ClientNumberID
GROUP  BY Client.FirstName,
          Client.LastName  

Thanks, Amy

Upvotes: 0

Views: 5372

Answers (2)

DRapp
DRapp

Reputation: 48139

It probably is based on doing a left join, but would you get bogus results if you have one invoice that has been paid multiple times (partial payments). Would those "Sum" equations count the invoice amount TWICE ex: One for each partial payment? I would try as follows.

SELECT 
      C.ClientNumberID,
      C.FirstName + ' ' + C.LastName AS ClientName, 
      SUM( I.InvoiceAmount ) TotalInvoices, 
      SUM( CP.PaymentAmount ) AS TotalAmountPaid, 
      SUM( I.InvoiceAmount ) - SUM( CP.PaymentAmount ) AS OutstandingPaymentAmount
   FROM
      Invoices I
         JOIN Clients C
            on I.ClientNumberID = C.ClientNumberID

      LEFT JOIN ClientPayments CP
         on I.InvoiceNumberID = CP.InvoiceNumberID
   GROUP BY
      I.ClientNumberID
   ORDER BY
      C.LastName,
      C.FirstName

Notice my GROUP BY is by the client number... What would happen otherwise, if you had 5 customers "William Smith", or "Robert Brown" which could be considered a "common name". You don't want to give one William Smith a statement that said he owed $5000 when he paid in full on all his purchases, while the invoices were actually split among other "William Smith" customers. THEN, the ORDER BY will put them into whatever order you need... or based on Outstanding amount descending for biggest collections at the top.

Upvotes: 2

Sergii Kudriavtsev
Sergii Kudriavtsev

Reputation: 10512

Try changing INNER JOIN to LEFT JOIN for the first join in your query

Upvotes: 2

Related Questions