4

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.

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.HR end)
         SUM(case when raaa.EN = 'No' AND raaa.HR <= raaa.WT then raaa.HR end)
         SUM(case when raaa.EN = 'No' 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 < raaa.field1 THEN raaa.field2 ELSE raaa.field1 END) >= 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;
4

You need to remove the outer case statement. It should be:

Select sum( case when ..... then .... end) from foo

You have

Select case when sum(case when.... then .... end) end from foo

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
   Case 
       When <condition > then sum(<column>)
        When <condition > then sum(<column >)
         Else sum(<column >)
         End
From foo
4
  • If I am following you that will put each sum() statement in its own pane when the query is returned. I am wanting each one of the case statements evaluated in order to determine what should be summed. – user2676140 Dec 20 '15 at 2:43
  • @user2676140 Did you mean column? If so yes each sum would get its own column. Otherwise you will need to pull the condition out of the sum and put it as a condition for the wrapping case statement you originally wrote. I'd advise you to think long and hard about that though because it seems like a debugging nightmare IMO. I'm on my phone so I can write a template of what that looks like if you really want but it will take a little bit and probably not be perfectly formatted – Erik Dec 20 '15 at 2:57
  • yes I mean column. Sorry for that. I understand it is a debugging nightmare, but that is the syntax I am needing. Thank you for the heads up on it tho. – user2676140 Dec 20 '15 at 3:00
  • @user2676140 something like that should work but no promises like I said I'm on my phone – Erik Dec 20 '15 at 3:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.