Can you use a CASE statement in a select statement...
# javascript
g
Can you use a CASE statement in a select statement in SQL?
I doing this: SELECT SUM(Debit - Credit) AS Tot But if the SUM(Debit-Credit) is greater than 0 I want to subtract 20 from it. And call it Tot_Less_Fee But if the SUM(Debit-Credit) is 0 I just want to leave it be as 0.
I tried this: SELECT "Tot" = CASE WHEN SUM(Debit-Credit) = 0 THEN 0 ELSE SUM(Debit-Credit) - 20 END But I realize now that the case logic needs to be on the "Debit-Credit" not the SUM() of them.
d
Yeah, it needs to be more like…
Copy code
SELECT SUM(CASE WHEN Debit - Credit <= 0 THEN 0
            ELSE Debit - Credit - 20 END) AS stuffSum
FROM table
g
So I am trying to SUM(Debit-Credit - 20) but only when the Debit-Credit is greater than 0.
OK, I just tried what you said. I think it may be working. It was returning 5655, so now when I eliminate the zero records I am getting 3915.
d
Yep, that should do it then (I updated the SQL to do a “<= 0” rather than just “= 0".
g
That might be doing what I need. Thanks!
d
So make sure to make that change in the first CASE statement.
g
Oh that might be good yeah.
Actually I might do <= 20.
Can't take a 20 fee if they only paid 10.
d
Sure, play with it now that you know how the syntax looks. Good luck!
g
But thanks for the help.
Something weird is happening. When getPartyFees.Tot comes out as an empty string it errors in CF. Even when I wrap it with the val() function.
val(getPartyFees.Tot) throws an error The value '' cannot be converted to a number.
I don't understand how the query returns an empty string. The CASE statement is inside a SUM() so shouldn't it always return aat least 0?
d
Unless you have some NULLs.
g
No, debit and credit are always zero or a value.
d
Try surrounding the field in a COALESCE (I think that is pretty standard across database engines?).
Something like…
Copy code
SELECT COALESCE(SUM(CASE WHEN Debit - Credit <= 0 THEN 0
            ELSE Debit - Credit - 20 END), 0) AS stuffSum
FROM table
g
OK
d
So, if this is all NULL, then return 0.