gpt4 book ai didi

sql - 使用 proc sql 高效转置

转载 作者:行者123 更新时间:2023-12-04 18:25:43 25 4
gpt4 key购买 nike

我想知道是否有可能在 sas 中使用 proc sql 有效地从宽转换为长。

我知道 proc transpose 比我在下面建议的方法要快得多。但我的目标之一是避免存储转置表。

例如,让我们说,我有 table1 作为

Id|   A|   B|   C|  D    
_____________________
1| 100|3500|6900| 10300
2| 200| 250| 300| 350
3| 150| 32| 400| 204
4| 200| 800|1400| 2000

我想把它变成
id|col1|  col2|
______________
1| A| 100|
1| B| 3500|
1| C| 6900|
1| D| 10300|
2| A| 200|
2| B| 250|
2| C| 300|
2| D| 350|
3| A| 150|
3| B| 32|
3| C| 400|
3| D| 204|
4| A| 200|
4| B| 800|
4| C| 1400|
4| D| 2000|

我可以做到这一点;

选择 id,'A' 作为 col1,A 作为 col2
从表 1
其中 A ~=""
联盟
选择 id,'B' 作为 col1,B 作为 col2
从表 1
其中 B ~=""
等等

但它非常低效。

任何的想法?谢谢。

最佳答案

如果您在 SAS , 使用 PROC TRANSPOSE对于这个选项。在 PROC SQL; 中没有特别好的方法可以做到这一点。虽然很多 SQL变体有自己的数据透视方式,SASPROC TRANSPOSE并希望您使用它。

SAS 数据步骤也非常有效地执行此操作,甚至可能比 PROC TRANSPOSE 更好.这是一个示例,包括创建注释中所述的 View 。

data want/view=want;
set have;
array vars a b c d; *array of your columns to transpose;
do _t = 1 to dim(vars); *iterate over the array (dim(vars) gives # of elements);
if not missing(vars[_t]) then do; *if the current array element's value is nonmissing;
col1=vname(vars[_t]); *then store the variable name from that array element in a var;
col2=vars[_t]; *and store the value from that array element in another var;
output; *and finally output that as a new row;
end;
end;
drop a b c d _t; *Drop the old vars (cols) and the dummy variable _t;
run;

关于sql - 使用 proc sql 高效转置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18320035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com