case when problem in query

  • I'm trying to evaluate several columns and have the answer populate a single column:

    case when col1 = 1 THEN 'yes' else (when col2 = 1 THEN 'no') end as column3

    I cannot get this to work and presume it's logic rather than sytax.

     

    Thanks in advance.......................

  • This doesn't match the syntax from BOL, for example:

     CASE ProductLine

             WHEN 'R' THEN 'Road'

             WHEN 'M' THEN 'Mountain'

             WHEN 'T' THEN 'Touring'

             WHEN 'S' THEN 'Other sale items'

             ELSE 'Not for sale'

          END,

    So, maybe you could state the rules in English and we could help structure this.  Are col1 and col2 mutually exclusive?  Could you have a case where clo1 = 1 and col2 = 1?  If so, what should the value then become?  You might be able to do something like:

     

    case col1

    when 1 then 'yes'

    else case col2

    when1 then 'no'

    end

    end

    What do you want to have happen when neither condition is true (or is that possible)?


    And then again, I might be wrong ...
    David Webb

  • nested case statements look like this

    case when col1 = 1 then 'yes' else

    case when col2 = 1 then 'no' else

    'maybe'

    end

    end

     

     


  • Thanks mrpolecat I was simply missing the correct number of 'end' statements..............

     

     

  • this may be cleaner

    case when col1 = 1 then 'yes'

    case when col2 = 1 then 'no'

    else

    'maybe'

    end

     

    note that if a condition is met then it stops looking so if col1 and col2 are 1 then you get 'yes'


  • Actually, there is one CASE too much in your SQL (probably just a typo):

    CASE WHEN col1 = 1 THEN 'yes'

    case  WHEN col2 = 1 THEN 'no' 

            ELSE 'maybe'

    END

  • Jeff,

    You have to try like this

    case when col1 = 1 THEN 'yes' else (case when col2 = 1 THEN 'no' end) end as column3

    Regards

    Kiruba Sankar.S

     

     

     

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

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