Using "like" inside a "case" statement with 2 different fields

22,651

Maybe:

SELECT 
    CASE 
      WHEN Col2 = 'N'
        OR Col1 LIKE '%c.txt'
          THEN '0'
      WHEN Col2 = 'Y'
          THEN '1'
    END AS Col3
  , * 
FROM Tabl1
Share:
22,651
user970225
Author by

user970225

Updated on July 09, 2022

Comments

  • user970225
    user970225 almost 2 years

    I have 2 fields in my table on which i need a case statement.

    Col1          Col2     Col3
    abc.txt       Y        0
    def.txt       N        0
    bbck.txt      Y        1
    

    The Col3 values are based on the Col1 and Col2 values in the following manner.
    Y = 1 and N = 0. So all the values in Col2 that are Y shall become 1 in col3, and Nin Col2 will become 0 in Col3, UNLESS the col1 value ends with %c.txt. As you can see since the abc.txt ends with %c.txt the value in col3 becomes 0.

    I know this can be done with a CASE statement nested maybe to get this done. Does anyone know how to?

    here's my code

    SELECT 
      CASE Col2
        WHEN 'Y' THEN '1'
        WHEN 'N' THEN '0'
      ELSE
    (CASE WHEN [Col1] LIKE '%c.txt' THEN '0'
     END)
      END
      AS Col3,
     *
    FROM Tabl1
    

    Hope this gives an idea

  • user970225
    user970225 over 12 years
    perfect answer. Thanks a lot.
  • ypercubeᵀᴹ
    ypercubeᵀᴹ over 12 years
    The WHEN Col2 = 'Y' THEN '1' can be replaced with ELSE '1' if Col2 has only Y and N values and nothing else.