Skip to main content
2 of 3
I changed the JOINS to LEFT JOINS to avoid dropping client who had no return checks.

This may not be the best way to do this but it will work.

SELECT c.ClientNo, c.ClientId, c.FullName,
    i.InvoiceTotalDue, i.InvoiceTotalBalance,
    r.ReturnChequeTotalDue, r.ReturnChequeTotalBalance
FROM Client_TBL c
LEFT JOIN (SELECT ClientNo, SUM(TotalDue) AS InvoiceTotalDue,
            SUM(TotalBalance) AS InvoiceTotalBalance
        FROM Invoice_TBL
        GROUP BY ClientNo) AS i
    ON c.ClientNo = i.ClientNo
LEFT JOIN (SELECT ClientNo, SUM(TotalDue) AS ReturnChequeTotalDue,
            SUM(TotalBalance) AS ReturnChequeTotalBalance
        FROM ReturnCheque_TBL) AS r
    ON c.ClientNo = r.ClientNo

And of course you could change the subqueries into CTEs. But basically you are going to collect the data pre join since otherwise you are probably going to get bad data (Client 2 for example will have Invoice info that is twice as large and ReturnCheque that is 3 times as large.)

Kenneth Fisher
  • 24.3k
  • 12
  • 61
  • 115