You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 17:11:11