I am trying to run the below query, but I am encountering this error:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
SELECT
IVCSUM1.ivcnum "Invoice Number"
,IVCSUM1.ivcgrsamt_amt "Gross Amount"
,IVCSUM1.ivcgrsamt_cur "Gross Amount Currency"
,SUM(ISNULL(IVCLINE1.ivclinextamt_amt, 0)
+ ISNULL((SELECT SUM(TaxAmount_amt) FROM MC_INVTAX WHERE ivclinref_oi = IVCLINE1.ivlnoi), 0)
+ ISNULL((SELECT SUM(amtchg_amt) FROM MC_INVCHG INVCHG1 WHERE IVCLINE1.ivlnoi = ivclinref_oi), 0)) "Invoice Line Amount"
FROM
MC_IVCSUM IVCSUM1 LEFT JOIN
MC_IVCLINE IVCLINE1 on IVCSUM1.ivsmoi = IVCLINE1.invsumm_oi
GROUP BY ivsmoi, ivcnum,IVCSUM1.ivcgrsamt_amt, IVCSUM1.ivcgrsamt_cur
I cannot join the tables MC_INVCHG and MC_INVTAX to the main query because it's causing duplicates in the IVCLINE1.ivclinextamt_amt field and the sum ends up being wrong.
Below is sample data I have pulled from the tables by joining them.
| Invoice Number | Line | Gross Amount | Tax amount | Change |
|---|---|---|---|---|
| 00 0001180 7 DEC03 | 1 | 80 | -5.04 | NULL |
| 00 0001180 7 DEC03 | 1 | 80 | 5.04 | NULL |
| 00 0001180 7 DEC03 | 2 | 40 | 2 | NULL |
What I am trying to accomplish with the query is, Invoice Line Amount = (80 + (5.04 + (-5.04)) + 0) + (40 + 2 + 0)
Since change is NULL for this, it is being considered as 0.
Is there a way to accomplish this in a different way?