简体   繁体   中英

CASE in WHERE expression using IN clause

I need that when var1 is equal to 'Y' the query show the result of the table with the column = 'Y', but when var1 = 'N' the result should be the data with column with 'Y' and 'N'. I need to put it in a where clause, cause I'm using oracle forms. I tried this way but the query didn't show any result:

SELECT  *
FROM    table
WHERE   column1 IN ((CASE WHEN var1 = 'Y' THEN q'[('Y')]'
                                  ELSE TO_CHAR(q'[('Y','N')]')
                                  END))

Can you help me? Thank you.

There is no need for CASE logic here, as you can fit this into a regular WHERE clause with boolean logic, wrapping each condition (var1 = 'Y', var1 <> 'Y') in a () group.

SELECT *
FROM table
WHERE
  (var1 = 'Y' AND column1 = 'Y')
  OR (var1 <> 'Y' AND column1 IN ('Y','N'))

Note, I used var1 <> 'Y' here to emulate your ELSE case, but if it is only two possible values Y/N you may use var1 = 'N' for clarity.

WHERE
  (var1 = 'Y' AND column1 = 'Y')
  OR (var1 = 'N' AND column1 IN ('Y','N'))

Actually, if Y/N are the only possible values for column1 , then it could be simplified to:

WHERE
  (var1 = 'Y' AND column1 = 'Y')
  -- Returns all rows for column1 if Y,N are the only possible values
  -- No need to explicitly filter it
  OR (var1 <> 'Y')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM