加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

用proc sql高效转置

发布时间:2020-12-12 16:22:54 所属栏目:MsSql教程 来源:网络整理
导读:我想知道是否可以使用sas中的proc sql有效地从宽到长转置. 我知道proc转置比我在下面建议的方法快得多.但我的目标之一是避免存储转置表. 比方说,我将table1作为 Id| A| B| C| D _____________________ 1| 100|3500|6900| 10300 2| 200| 250| 300| 350 3| 150|
我想知道是否可以使用sas中的proc sql有效地从宽到长转置.

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

比方说,我将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
来自table1
其中A~ =“”
联盟
选择id,’B’为col1,B为col2
来自table1
其中B~ =“”
等等

但效率很低.

任何想法?谢谢.

解决方法

如果您使用SAS,请使用PROC TRANSPOSE作为此选项.在PROC SQL中没有特别好的方法可以做到这一点;虽然许多SQL变种都有自己的数据透视方式,但SAS有PROC TRANSPOSE并希望您使用它.

SAS datastep也非常有效,甚至可能比PROC TRANSPOSE更好.这是一个示例,包括创建注释中所述的视图.

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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读