在SAS中使用PROC SQL将表从long转换为wide

时间:2015-01-16 01:57:07

标签: sql sas transpose

我正在审查Life Imitates Art:ODS输出数据集,看起来像http://www.mwsug.org/proceedings/2013/BB/MWSUG-2013-BB12.pdf的列表输出,其中作者强制从PROC输出的数据集类似于它们的表格描述输出。作者的代码是:

proc print data=sashelp.bweight(obs=5); run;

Proc Tabulate MISSING
Data=sashelp.bweight
Out=outequals(drop=_:);
Class ed smoke;
Tables ed, smoke /
 box="(Table in ODS Destination)";
Run;

Proc Print
Data=outequals noobs;
Run;

Proc Transpose
Data=outequals
 Out=twowaytable(drop=_:)
 prefix=smoke;
 By ed;
 ID smoke;
Var N;
Run; 

我想知道是否有一种使用proc sql的漂亮方法,因为在过去,似乎proc转置是不灵活的,因为问题变得更加复杂。我想出了一个解决方案(下面),但我不知道是否可以更有效地使用PROC SQL。

proc sql ; 
create table col2_a as 
select * from outequals where smoke eq 1 and ed = 0 
outer union 
select * from outequals where smoke eq 1 and ed = 1 
outer union 
select * from outequals where smoke eq 1 and ed = 2 
outer union
select * from outequals where smoke eq 1 and ed = 3
;
quit;

proc sql ; 
create table col2_b as 
select monotonic() as key, * 
from col2_a 
; quit;

proc print data=col1_b ; run;

proc sql ; 
create table report as 
select 
a.ed as ed,
a.N as Smokers_HC,
b.n as NonSmokers_HC
from 
col1_b a join col2_b b 
on a.key eq b.key
;quit;

1 个答案:

答案 0 :(得分:0)

我更喜欢转置解决方案作为其动态,Proc SQL需要对答案进行硬编码。

这里' a' Proc SQL解决方案:

proc sql;
create table want as
select ed, sum(smoke=1) as smoke1, sum(smoke=0) as smoke0
from sashelp.bweight
group by ed
order by ed;
quit;