“IN” condition at CASE WHEN on WHERE CLAUSE?

回眸只為那壹抹淺笑 提交于 2019-12-10 16:29:05

问题


I have an complex situation. I want to write an sql query including "case when" condition on "where clause".

Just like that:

SELECT *
FROM <table>
WHERE
<Column1> in
   CASE <Column2>
      WHEN 1 THEN ('OP', 'CL') 
      WHEN 0 THEN ('RE', 'ST')
END

Column1 must be "in", not "=". Because there is multiple value at condition for Column1. That query returns "Incorrect syntax near ','." error.

Can you give me any suggestion? (Sorry for my bad English.)

EDIT : I think I misunderstood. If Column2 is 1, condition must like that "IN ('OP', 'CL')" else Column1 is 2, condition must like that "IN ('RE', 'ST')".


回答1:


You don't need a CASE expression for that, you can just use OR like this:

SELECT *
FROM <table>
WHERE (Column2 = 1 AND Column1 IN ('OP', 'CL')) OR
    (Column2 = 0 AND Column1 IN ('RE', 'ST'))



回答2:


Select * from table where <Column1> in (Select case <Column2> when 1 then ('OP','CL') when
0 then  ('RE','ST'))


来源:https://stackoverflow.com/questions/12424551/in-condition-at-case-when-on-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!