如何对同一组的多行使用 Proc Sql 'Case When' 条件

问题描述 投票:0回答:1

我想为一个变量创建三个指标。我有一个如下所示的数据集:-

ID    Group  Color
1763    A     Red
1763    A     Yellow
6372    B     Red
0498    A     Red

我想考虑当我有两行具有相同 ID 且在颜色列(红色或黄色)中具有不同值的情况,并用附加指示器对其进行标记。然后在我的输出数据集中具有不同的 ID。

proc sql;
create table want as 
  select a.ID
  a.Qty
  (case when b.Group = 'A' then 'R'
        when b.Group = 'B' then 'L' 
        when b.Color = 'Red' AND b.Group ='A' then 'R/L'
        when b.Color = 'Yellow' AND b.Group = 'B' then 'R/L'
        else 'X' end) as Category
 from work.test a
   left join (select distinct ID, Group, Color from work.have) b
        on a.ID=b.ID
;
quit;

我希望数据集看起来像这样:-

ID      Qty   Category
1763     28     R/L
6372     30     L
3908     41     X
0498     32     R
sas proc-sql
1个回答
0
投票

根据您的问题,了解代码示例中提供的两个源数据集

test
have
的内容将很有用。然而,我试图通过猜测
test
表可能包含的内容来展示如何实现这一点:

data have;
input ID : $4. Group : $1. Color :$8.;
datalines;
1763    A     Red
1763    A     Yellow
6372    B     Red
0498    A     Red
;
run;

data test;
input ID : $4.;
if id='1763' then do i=1 to 28; output; end;
if id='6372' then do i=1 to 30; output; end;
if id='0498' then do i=1 to 32; output; end;
if id='3908' then do i=1 to 41; output; end;
drop i;
datalines;
1763
6372
0498
3908
;
run;

proc sql;
    /* Count the distinct colours in the have dataset by id, group */
    create table id_color_count as
    select ID, group, count(distinct color) as diff_color
    from work.have
    group by id, group;
    
    /* Conditionally set category names based on count of colours first, then groups */
    /* if the id is not in the have dataset set the category to X */
    create table aggregate as
    select
    test.*, case when diff_color > 1 then 'R/L'
    when group = 'A' then 'R'
    when group = 'B' then 'L'
    else 'X'
    end as category
    from test
    left join
    id_color_count
    on test.id = id_color_count.id;
    
    /* Group the data and use count to output the Qty */
    create table want as
    select id,
    count(*) as qty
    category,
    from
    aggregate
    group by id, category;
quit;
© www.soinside.com 2019 - 2024. All rights reserved.