I'm trying to fix a bug in inherited code. This query is meant to bring back an amex_meal_amount_total of $33
, but it is giving $99
. The problem is with the second join - there are three associated items in the EE table
that is making the aggregate sum up three rows.
SELECT ER.report_id,
Isnull(Sum(EE_AMEX.meal_amount), 0) AS amex_meal_amount_total
FROM expense_report ER (nolock)
LEFT OUTER JOIN expense_expense EE_AMEX (nolock)
ON ER.report_id = EE_AMEX.report_id
AND EE_AMEX.line_item_type_id = 1
LEFT OUTER JOIN expense_expense EE_OOP (nolock)
ON ER.report_id = EE_OOP.report_id
AND EE_OOP.line_item_type_id = 2
WHERE er.report_id = 9733
GROUP BY ER.report_id
It is clear to me that the developer was trying to use a table alias in the join (ex. EE_AMEX) to limit the sum
function to the condition in the join.
There is only one row in the EE table
with the line_item_type_id 1
for this ID
. When I remove the other join statement, it brings back the expected $33
.
SELECT ER.report_id,
Isnull(Sum(EE_AMEX.meal_amount), 0) AS amex_meal_amount_total
FROM expense_report ER (nolock)
LEFT OUTER JOIN expense_expense EE_AMEX (nolock)
ON ER.report_id = EE_AMEX.report_id
AND ee_oop.line_item_type_id = 1
WHERE er.report_id = 9733
GROUP BY ER.report_id
Is there a straightforward fix to this, or do I need to completely restructure the queries?
Table structure:
Trying to keep it simple for this question
expense_report:
report_id (PK)
expense_expense:
report_id (FK, one to many)
meal_amount (can be multiple rows with meal amounts per report_id)
taxi_amount (example of other charges)
line_item_type_id (1 is AMEX, 2 is OOP, can be any per row)
In this case the ER has one associated row in expense_expense with a meal charge of $33, so that was what I would expect.
However, there were three associated rows for other charges such as taxi, etc.
When running the query it sums it for three rows, thus the unexpected $99.
Thanks.