2017-04-06 155 views
0

我有一个简短的向量,我希望能够在PROC SQL中的case语句中使用。我没有从我的研究中找到任何东西。让我用一个例子来解释。是否可以在PROC SQL case语句中使用向量?

我的手机品牌的载体:

phone_brand 
nokia 
samsung 
apple 
microsoft 
sony 
motorolla 

我想要与更多的数据的另一个表中的PROC SQL语句,但我想创建一个指标,会告诉我,如果的phone_brand场该表与矩阵匹配。因此,代码的想法是这样的:

proc sql; 
create table test as 
select id 
     ,date 
     ,case when index(home.phone_brand,'vector values') > 0 then 1 else 0 
     end as vector_ind 
from ods.home; 
quit; 

我需要这个,因为我有载体将是动态的,但没有任何排序键来识别品牌。所以我必须使用索引函数来搜索匹配。如果我不能找到一种方法,与我觉得我唯一的选择将是手动每次更新代码的矢量的变化是这样的数据矢量做到这一点:

,case when index(home.phone_brand,'nokia') > 0 then 1 
    when index(home.phone_brand,'samsung) > 0 then 1 
    when index(home.phone_brand,'apple) > 0 then 1 
    ....... 
    else 0 end as vector_ind 

这将是繁琐,如果矢量中的品牌数量显着增加,则难以扩展。

回答

2

我认为你正在寻找IN操作符。

proc sql; 
select name , sex , age 
    , name in ('Alfred','Carol') as vector_ind 
from sashelp.class 
; 

您也可以存储在列表宏变量

%let vector = 'Alfred','Carol' ; 

,然后在查询中使用宏变量。

select name , sex , age 
    , name in (&vector) as vector_ind 
from sashelp.class 
; 

或将其存储在数据集中,

create table vector as 
    select name 
    from sashelp.class 
    where name in (&vector) 
; 

和使用子查询。

select name , sex , age 
    , name in (select name from vector) as vector_ind 
from sashelp.class 
; 

或者你也可以结合过去两年。将值存储在数据集中,但使用它来构建一个宏查询以用于查询。

select catq('1sa',name) 
    into :vector separated by ',' 
    from vector 
; 
+0

这完美的作品!这只能找到完全匹配吗?我通常使用'索引'来解决数据中的不一致(不一致的缩写和拼写错误)。你知道我在这段代码中如何调整? – Jarom

+1

IN是完全匹配,但您可以在(%upcase(&vector))中使用'upcase(name)'来避免大小写问题。 – Tom