I want to run a query on some fields of the table, but I cant understand how to do it. I have the condition that first I need to check value of col1 , if it is 'W', then I need to check colA having values in ('1','2'), if it is not 'W', then I need to check colB having values in ('1','2'). This condition to check ('1','2') applies same to both colA and colB, just depending on the value of col1.
I tried using this, but obviously this is incorrect.
SELECT * FROM tbl
WHERE CASE WHEN col1= 'W' THEN (colA IN ('1','2')) ELSE (colB IN ('1','2')) END
So how can I do it in a single query without using Unions etc.
You don't need CASE
, just put all your boolean logic together in one expression.
SELECT *
FROM T
WHERE
(Col1 = 'W' AND ColA IN ('1', '2'))
OR
(Col1 <> 'W' AND ColB IN ('1', '2'))
;
Sql Server-2014 : Use CASE to choose column to be used in WHERE clause based on condition-
SELECT * FROM tab1
WHERE
(CASE WHEN col1= 'W' THEN colA ELSE colB END) in ('1', '2');
Tested on SqlServer-2014 . image attached
MySql : Use IF() function to choose column to be used in WHERE clause based on condition-
SELECT * FROM tab1
WHERE
IF(col1='W', colA, colB) in ('1', '2');
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.