我正在尝试在IN子句中编写一个case语句。
Channel列包含三个值ACT,REN,REP。我想选择多个值,但我得到的结果只有一个值。
select * from tbl
WHERE tbl.Channel IN (select
case when @ACT =1 then 'ACT'
when @REN =1 then 'REN'
when @REP =1 then 'REP' END)
我应该在这做什么改变?
答案 0 :(得分:4)
不要结束你的案子。您将返回3列。你只想要一个。
select * from tbl
WHERE tbl.Channel = case when @ACT =1 then 'ACT'
when @REN =1 then 'REN'
when @REP =1 then 'REP'
else NULL END
答案 1 :(得分:3)
这样可以正常工作。 SQL Fiddle
唯一的变化是删除select
,因此in子句的输入是3个值,而不是包含三列的单个行。
如果变量不是1,则隐式else null
不会导致in
子句出现问题。
SELECT *
FROM tbl
WHERE tbl.channel IN ( CASE
WHEN @ACT = 1 THEN 'ACT'
END, CASE
WHEN @REN = 1 THEN 'REN'
END, CASE
WHEN @REP = 1 THEN 'REP'
END )
答案 2 :(得分:1)
您可以在没有case
的情况下编写该条款:
select *
from tbl
where (tbl.Channel 'ACT' and @ACT = 1) or
(tbl.Channel = 'REN' and @REN = 1) or
(tble.Channel = 'REP' and @REP = 1);
您的select
语句不正确,应该返回错误。 select
子句中的in
语句不允许返回多个列。
答案 3 :(得分:1)
这是一个替代方案,可让您在没有IN
运算符的情况下执行选择:
select * from tbl
WHERE (tbl.Channel='ACT' AND @ACT=1)
OR (tbl.Channel='REN' AND @REN=1)
OR (tbl.Channel='REP' AND @REP=-1)
如果您必须使用IN
运算符,则应该能够使用UNION ALL
构建查询,如下所示:
select * from tbl
WHERE tbl.Channel IN (
select case when @ACT =1 then 'ACT' END FROM DUAL
UNION ALL
select case when @REN =1 then 'REN' END FROM DUAL
UNION ALL
select case when @REP =1 then 'REP' END FROM DUAL)