procsql-根据另一列的条件为一列赋值

g6baxovj  于 2021-07-24  发布在  Java
关注(0)|答案(4)|浏览(418)

当months=1时,我想根据“ind”列中的值在新列中赋值;

idnum1  months  ind new_col
1       1       X   X
1       2       X   X
1       3       Y   X
1       4       Y   X
1       5       X   X
2       1       Y   Y
2       2       Y   Y
2       3       X   Y
2       4       X   Y
2       5       X   Y

下面的查询只分配值x,其中months=1,但我要在所有行中为所有id添加新的列-

create table tmp as
select t1.*, 
case when months = 1 then ind end as new_col
from table t1;

我正在尝试用procsql在sas中实现它;

yuvru6vn

yuvru6vn1#

理想情况下,您可以在数据步骤中使用retain:

data want;
set have;

retain new_var;
if month=1 then new_var = ind;
run;

sql在这方面不如数据步骤好。
但是假设变量id重复,那么这就行了。如果不是这样,那么您确实需要数据步方法。

proc sql;
create table want as 
select *, max(ind) as new_col
from have
group by ID;
quit;

编辑:如果你想保留每个id的第一个,只需使用第一个。而不是月=1。

data want;
set have;
by ID;
retain new_var;

if first.id then new_var = ind;
run;
ltskdhd1

ltskdhd12#

健壮的 Proc SQL 声明,处理可能重复的第一个月的情况,选择最低 ind 分发给小组

data have; input
idnum1  months  ind $ new_col $; datalines;
1       1       X   X
1       2       X   X
1       3       Y   X
1       4       Y   X
1       5       X   X
2       1       Y   Y
2       2       Y   Y
2       3       X   Y
2       4       X   Y
2       5       X   Y
3       1       Z   .
3       1       Y   .
3       1       X   .
3       2       A   .
;

create table want as
select 
  have.idnum1, months, ind, new_col, lowest_first_ind
from
  have
join 
  ( select idnum1, min(ind) as lowest_first_ind from 
    (
    select idnum1, ind 
    from have
    group by idnum1
    having months = min(months)
    )
    group by idnum1
  ) value_seeker
on
  have.idnum1 = value_seeker.idnum1
;

7cjasjjr

7cjasjjr3#

可以使用窗口函数:

select t1.*,
       max(case when months = 1 then ind end) over (partition by id) as new_col
from t1;
g52tjvyc

g52tjvyc4#

如果每个小组只有一个月=一次观察,那么就使用简单的连接。

create table WANT as
  select t1.*,t2.ind as new_col 
  from table t1
  left join (select idnum1,ind from table where month=1) t2
    on t1.idnum1 = t2.idnum1
;

相关问题