So ive written a query adding to one someone else built to get some correct amounts for payments. All is well until i bring a tax table into it. The problem is when i add the amounts together (ie PaidAmount+TaxAmount+AdvancedFees) the records with taxes added automatically yield two rows: a sum with taxes and one without.
I put the tax portion into a With Statement and linked to another table but it isn't solving the problem. A couple various methods i tried resulted in only records with taxes populating results. Im suspecting this has something to do with the initial calculation in the With Statement, but even if i do this in the main SELECT statement, it brings in the same numbers.
Thank you in advance for any advice/assistance.
here's the with Statement
;With CaseTaxes AS
(SELECT DISTINCT
cst.[CaseServiceID],
cst.[TaxTypeProgKey],
cs.PurchaseOrderID,
ISNULL(CASE WHEN AVG(cst.[Amount]) > 0 AND cst.[TaxTypeProgKey] =
'STATE' OR cst.[TaxTypeProgKey] = NULL THEN AVG(cst.[Amount])
--WHEN cst.[TaxTypeProgKey] = 'HST' OR cst.[TaxTypeProgKey] = 'GST'
OR cst.[TaxTypeProgKey] = 'PST' OR cst.[TaxTypeProgKey] = 'QST' THEN 0
--WHEN AVG(cst.[Amount]) = 0 then 0
--ELSE 0
END,0) AS 'CaseTax',
sum(clm.[PaidAmount]) as 'PaidAmt'
AND HERE IS THE CALCULATED FIELD TO SUM UP ALL THE NUMBERS
FORMAT(cata.[PaidAmt]+ISNULL(cata.[CaseTax],0)+ISNULL(af.[AdvanceFee],0)-
ISNULL(cs.[TaxWithholding],0),'c', 'en-au') as 'VendorPaid'