如何为每个新列值在行中添加常量值?

时间:2018-07-18 15:53:49

标签: sql excel sas

我有如下数据:

number    letter
1          a
1          b
1          c
2          d
2          e
3          f
3          g
3          h
3          i

我想在“数字”字段的每个新值处插入3个新行(x,y,z),这样看起来像这样:

number    letter
1          a
1          b
1          c
1          x
1          y
1          z
2          d
2          e
2          x
2          y
2          z
3          f
3          g
3          h
3          i
3          x
3          y
3          z

帮助?

4 个答案:

答案 0 :(得分:1)

在SAS中,您只需在数据步骤中添加一些OUTPUT语句即可。

data want ;
  set have ;
  by number;
  output;
  if last.number then do letter='x','y','z';
    output;
  end;
run;

答案 1 :(得分:0)

您可以在SQL中完成所有这些操作。以下内容适用于几乎所有数据库:

select number, letter
from t
union all
select distinct number, 'x' 
from t
union all
select distinct number, 'y' 
from t
union all
select distinct number, 'z' 
from t;

答案 2 :(得分:0)

在proc Sql中,您可以进行交叉联接,然后进行联合,如下所示;

data have1;
input id val$;
datalines;
1          a
1          b
1          c
2          d
2          e
3          f
3          g
3          h
3          i
;
run;

data have2;
input val $;
datalines;
x
y
z
;
proc sql;
create table want as 
select * from have1
union 
select id, val from 
(select distinct id from have1)a
cross join 
(select val from have2)b;

答案 3 :(得分:0)

数据步骤解决方案,而不是SQL。 使用明确的OUTPUT语句来控制输出。

data have;
    input id val$;
    datalines;
1          a
1          b
1          c
2          d
2          e
3          f
3          g
3          h
3          i
;
run;

data want;
    set have;
    by id;
    output;

    if last.id then
        do;

            do val='x', 'y', 'z';
                output;
            end;
        end;
run;