简体   繁体   中英

How to create columns using values from one column in SQL (PROC SQL in SAS)

I am using PROC SQL on SAS.

The table on the left is the one I have. I want to create the table on the right, ie creating as many columns as there are different values for the column 'value' (they are known and only 3 of them : "a", "b" and "c").

The value is the one from "col". If it doesn't exist for corresponding 'value', default value is 0. I tried using GROUP BY and CASE, but I still wound up with a table with 6 lines.

表

Thanks in advance.

In SAS, you can use proc sql :

proc sql;
    select id,
           sum(case when value = 'a' then col else 0 end) as col_a,
           sum(case when value = 'b' then col else 0 end) as col_b,
           sum(case when value = 'c' then col else 0 end) as col_c
    from t
    group by id;

Consider proc_transpose which is dynamic to any length of values:

** TRANSPOSING DATA SET;
proc sort data=input out=input;
    by id;
run;

proc transpose data=input out=input_transposed(drop=_name_) prefix=col_;
    by id;          
    var col;    
    id value;
run;

SAS 输出

To replace missing for zeros run across arrays of numeric columns to call coalesce . Again, this scales to hundreds of potential columns:

data input_transposed;
    set input_transposed;

    array num(*) _numeric_;
    do _n_ = 1 to dim(num);
    num(_n_) = coalesce(num(_n_), 0);
end;

SAS 表输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM