I have a database with information from several companies that record their data differently. To mark what is a credit memo/finance charge/invoice/etc- 3 companies use a certain field, while 3 of the other companies just rely on positive vs negative values.
But I need totals- and I will need them often… so I thought Sum Case statement was the way to go.
I’ve read through many similar questions on this site- but I am not finding a fix that works. Most are either not for SSMS or don’t address multiple qualifiers.
I can get the individual totals company by company- but it seems like there should be a way to do it all in one go. So here’s what I cam e up with:
SUM(CASE WHEN((ff29='invoice' AND (import_source_id=1 OR import_source_id=2 OR import_source_id=6)) OR (amount_invoice>0 AND (import_source_id=4 OR import_source_id=5 OR import_source_id=8)) THEN CAST(amount_invoice AS DECIMAL(18,2)) ELSE 0 END) AS 'Debits', SUM(CASE WHEN((ff29='credit memo' AND (import_source_id=1 OR import_source_id=2 OR import_source_id=6)) OR (amount_invoice<0 AND (import_source_id=4 OR import_source_id=5 OR import_source_id=8)) THEN CAST(amount_invoice AS DECIMAL(18,2)) ELSE 0 END) AS 'Credits'
I expected my results to show as 2 columns (Debits & Credits) for each company (import_source_id)- but only include certain results- which is recorded differently by each company that is in my database.
Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword ‘THEN’. Msg 102, Level 15, State 1, Line 10 Incorrect syntax near ‘=’. Msg 102, Level 15, State 1, Line 11 Incorrect syntax near ‘=’.
I also do not know what to put at the beginning end of the code in these questions boxes that let’s it show up nicely separated in that gray box like everyone else. So- I apologize for that.
Advertisement
Answer
Remove the opening parentheses after both WHEN
s (or add a closing parenthesis before THEN):
SUM(CASE WHEN (ff29='invoice' AND (import_source_id=1 OR import_source_id=2 OR import_source_id=6)) OR (amount_invoice>0 AND (import_source_id=4 OR import_source_id=5 OR import_source_id=8)) THEN CAST(amount_invoice AS DECIMAL(18,2)) ELSE 0 END) AS 'Debits', SUM(CASE WHEN (ff29='credit memo' AND (import_source_id=1 OR import_source_id=2 OR import_source_id=6)) OR (amount_invoice<0 AND (import_source_id=4 OR import_source_id=5 OR import_source_id=8)) THEN CAST(amount_invoice AS DECIMAL(18,2)) ELSE 0 END) AS 'Credits'
Also why not use IN to simplify:
SUM(CASE WHEN (ff29='invoice' AND (import_source_id IN (1,2,6)) OR (amount_invoice>0 AND (import_source_id IN (4,5,8)) THEN CAST(amount_invoice AS DECIMAL(18,2)) ELSE 0 END) AS 'Debits', SUM(CASE WHEN (ff29='credit memo' AND (import_source_id IN(1,2,6)) OR (amount_invoice<0 AND (import_source_id(4,5,8)) THEN CAST(amount_invoice AS DECIMAL(18,2)) ELSE 0 END) AS 'Credits'