Nested CASE statements

  • I am trying to code an Excel nested IF statement in SQL Server 2008. It is of the form:

    =((IF(Y4=1,"6.0",IF(Y4=2,"5.4",IF(Y4=3,"4.2",IF(Y4=4,"3.1",IF(Y4=5,"2.2",IF(Y4=6,"1.0")))))))

    I think I need to use a nested CASE statement but am not sure of the syntax. Could anybody help?

  • What are you trying to do in SQL? I'm thinking that there might be a better way without using a CASE statement.

    Can you give us an example of what you're trying to do?

    +--------------------------------------------------------------------------------------+
    Check out my blog at https://pianorayk.wordpress.com/

  • DECLARE @Y4 AS INT

    SET @Y4 = 3

    SELECT

    CASE

    WHEN @Y4 = 1 THEN '6.0'

    WHEN @Y4 = 2 THEN '5.4'

    WHEN @Y4 = 3 THEN '4.2'

    WHEN @Y4 = 4 THEN '3.1'

    WHEN @Y4 = 5 THEN '2.2'

    WHEN @Y4 = 6 THEN '1.0'

    END AS 'Result'

  • I have a table containing numerical codes that correspond to patients answers to a post-operative well-being questionnaire. For example:

    Question 7

    "Is your mobility better now you have had your surgery?"

    Answers

    "Much better" = 1

    "Just the same" = 2

    "Worse" = 3

    The numerical values are then entered into a formula such as I gave in my example to calculate scores for well-being categories like Physical Function, Body Pain and General Health.

    Does this clarify at all?

    Thanks.

  • pbaker-1004855 (11/3/2010)


    Does this clarify at all?

    A little bit. Jeff's CASE example above is correct, if you want to go with that.

    Otherwise, if I have time to digest your scenario and am able to come up with something better (not sure if I can -- I have work to do myself, after all ;-)), I'll try to throw in my $0.02.

    Table and query examples would be helpful, if you can put that together.

    +--------------------------------------------------------------------------------------+
    Check out my blog at https://pianorayk.wordpress.com/

  • Many thanks to you both Jeff and Ray.

Viewing 6 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic. Login to reply