使用不同的 table 中可用的列名称值创建 table

Create a table with column name values available in a different table

SAS Datastep- 使用不同 table 中可用的列名称值动态创建 table。

示例: 我的 Source_Table 看起来像 |字段编号|字段名称| |1|一个| |3|乙| |2| C|

/*Dynamic table creation*/
%let  s1=;
/*Column lenght should be 30 characters so I am creating a dummy variable*/
%let Dummy= 'Dummy_Dummy_Dummy_Dummy_Dummy_Dummy_Dummy';

proc sql;
    create table TEMP as 
        select 'Hi' as Work from Temp_table where 1=2
    ;
quit;

proc sort data =   Source_table
    by Field_No;
run;

proc sql;
    select Dummy||" as "||fld into :s1 seperated by "," from
    (select "&Dummy" as Dummy,substr(strip(upcase(field_name)),1,30)) as FLD 
from Source_table)
    ;
quit;

proc sql;
    create table target_table  as 
        select "&Dummy." as value_1,&s1 from TEMP where 1=2;
quit;

目标 table 应该是 |A|B|C|

不太清楚你在问什么;您特别提到使用 SAS 数据步骤,但是您的代码示例使用 PROC SQL - 使用哪个有关系吗?另外,请注意您的输入有 |Field No|Field Name|1|A|3|B|2|C|但是你说输出应该按 A-B-C 的顺序 - 字段是否应该按 Field_No 指定的顺序?

无论如何,这里有一些非常简单的代码:

    * Create the input data set;
    data source_table;
      field_no = 1; field_name = 'A'; output;
      field_no = 3; field_name = 'B'; output;
      field_no = 2; field_name = 'C'; output;
    run;

    * Derive the list of field/variable names, in the correct order;
    proc sql noprint;
      select field_name into :var_list separated by ' '
        from source_table
        order by field_no
      ;
    quit;

    * Create the output data set using the variable list created above;
    data target_table;
      length &var_list $ 30;
    run;

如果有其他要求不允许使用这种简单的方法,请更新问题以解释原因。此代码将所有指定的列创建为长度为 30 的字符变量,但可以轻松扩展以允许在 source_table 中指定每个变量的类型、长度和标签 - 这种事情全部完成我工作的时间。

谢谢克里斯。

我试过类似的东西,它奏效了

proc sql noprint;
select catt(Field_name, ' char(30)') into :Col_name separated by ', '
from Source_table
order by field_no;

create table Target_table
(Value_1 char(30), &Col_name);
quit;