My query works fine until I add in the estimate tables, where my data duplicates.
Below is my table structure:
Jobs
| ID | JobNumber |
|----|-----------|
| 1 | J200 |
| 2 | J201 |
Job_Invoices
| ID | InvoiceNumber | JobID |
|----|---------------|-------|
| 10 | I300 | 1 |
| 11 | I301 | 2 |
Invoice_Accounts
| ID | InvoiceId | AccountID | Amount |
|----|-----------|-----------|--------|
| 23 | 10 | 40 | 200 |
| 24 | 10 | 40 | 300 |
| 25 | 10 | 41 | 100 |
| 26 | 11 | 40 | 100 |
Estimates
| ID | JobID |
|----|-------|
| 50 | 1 |
Estimate_Accounts
| ID | EstimateID| AccountID | Amount |
|----|-----------|-----------|--------|
| 23 | 50 | 40 | 100 |
| 24 | 50 | 40 | 100 |
Accounts
| ID | Name |
|----|------|
| 40 | Sales|
| 41 | EXP |
I am trying the below:
SELECT
J.JobNumber,
A.Name AS "Account",
SUM(JA.Amount) AS 'Total Invoiced',
SUM(EA.Amount) AS 'Total Estimated',
FROM
Job J
LEFT JOIN
Job_Invoices JI ON JI.JobID = J.ID
LEFT JOIN
Estimates E ON E.JobID = J.ID
LEFT JOIN
Estimate_Accounts EA ON EA.EstimateID = E.ID
INNER JOIN
Invoice_Accounts JA ON JA.InvoiceId = JI.ID
INNER JOIN
Accounts A ON A.ID = JA.AccountID
GROUP BY
J.JobNumber, A.Name, JA.Amount
ORDER BY
J.JobNumber
This is what I am hoping to achieve:
| JobNumber | Account | Total Invoiced | Total Estimated |
|-----------|-----------|----------------|-----------------|
| J200 | EXP | 100 | 0 |
| J200 | Sales | 500 | 200 |
| J201 | Sales | 100 | 0 |
This works fine if before I add the Estimates and Estimate_Accounts tables, my result looks like the above (without the Total Estimate) column.
However, when I try adding the Total Estimated column by joining the Estimates and Estimate_Accounts tables, Total Invoiced and Total Estimated values double, to something like this:
| JobNumber | Account | Total Invoiced | Total Estimated |
|-----------|-----------|----------------|-----------------|
| J200 | EXP | 200 | 0 |
| J200 | Sales | 1000 | 400 |
| J201 | Sales | 200 | 0 |