在SAS SQL的WHERE子句中嵌套CASE与IN语句是否可行?
SAS SQL中WHERE子句使用CASE配合IN的写法问题
你的这种写法不可行,原因是SQL里的CASE属于标量表达式,只能返回单个值,没办法返回像('0', '1', '2')这样的多值集合,直接这么写会触发语法解析错误。
正确改写方式
可以把逻辑拆成条件分支组合,或者用CASE生成判断标志,两种常见写法如下:
写法1:拆分条件分支(更直观)
proc sql; connect to $$$$$; create table test1 as select * from $$$$$ ( select line1, line2 from $$$$$ where -- line2=1时,排除line1为0/1/2的记录 (line2 = 1 and line1 not in ('0', '1', '2')) or -- line2≠1时,排除line1为3的记录 (line2 <> 1 and line1 not in ('3')) ); quit;
写法2:用CASE生成判断标志
proc sql; connect to $$$$$; create table test1 as select * from $$$$$ ( select line1, line2 from $$$$$ where case -- 符合排除条件的返回0,否则返回1 when line2 = 1 and line1 in ('0', '1', '2') then 0 when line2 <> 1 and line1 in ('3') then 0 else 1 end = 1 ); quit;
补充说明
如果是通过SAS连接的外部数据库(比如Oracle、SQL Server),改写逻辑同样适用,因为这是SQL标准的限制,不是SAS独有的问题。
内容的提问来源于stack exchange,提问作者trophez
相关产品推荐
相关产品推荐

