patternMinor
Nest SUM() Function Inside Case Statement?
Viewed 0 times
casestatementnestfunctionsuminside
Problem
I am trying to run this syntax, but I get an error of
Msg 4145, Level 15, State 1, Line 9
An expression of non-boolean type specified in a context where a condition is expected, near 'SUM'.
And this is my syntax, just trying to conditionally execute a SUM() based off the criteria.
EDIT
I know that this will work, just can't seem to get syntax correct for the above
Msg 4145, Level 15, State 1, Line 9
An expression of non-boolean type specified in a context where a condition is expected, near 'SUM'.
And this is my syntax, just trying to conditionally execute a SUM() based off the criteria.
SELECT
CASE WHEN
SUM(case when raaa.EN = 'Yes' AND raaa.HR >= raaa.WT then raaa.WT end)
SUM(case when raaa.EN = 'Yes' AND raaa.HR = raaa.WT then raaa.WT end)
END AS HR
FROM
ranaboveaboardabout raaa;EDIT
I know that this will work, just can't seem to get syntax correct for the above
Select
CASE WHEN
SUM(raaa.field1) / SUM(CASE WHEN raaa.field2 = 16.23 THEN 20
ELSE SUM(raaa.field1) / SUM(CASE WHEN raaa.field2 < raaa.field1 THEN raaa.field2 ELSE raaa.field1 END)
END AS nestedSUM
FROM
ranaboveaboardabout raaa;Solution
You need to remove the outer case statement. It should be:
You have
The when clause expects something that will resolve to either true or false. That's what your error message is trying to tell you.
I'm still not 100% sure what your end goal is but you either need to remove the wrapping case statement like I said above or pull the case condition out of the sum.
Select sum( case when ..... then .... end) from fooYou have
Select case when sum(case when.... then .... end) end from fooThe when clause expects something that will resolve to either true or false. That's what your error message is trying to tell you.
I'm still not 100% sure what your end goal is but you either need to remove the wrapping case statement like I said above or pull the case condition out of the sum.
Select
Case
When then sum()
When then sum()
Else sum()
End
From fooCode Snippets
Select sum( case when ..... then .... end) from fooSelect case when sum(case when.... then .... end) end from fooSelect
Case
When <condition > then sum(<column>)
When <condition > then sum(<column >)
Else sum(<column >)
End
From fooContext
StackExchange Database Administrators Q#124162, answer score: 4
Revisions (0)
No revisions yet.