为同一组生成唯一ID

时间:2018-06-20 06:01:16

标签: sas sas-macro

我有数据集,

CustID  Rating
1   A
1   A
1   B
2   A
2   B
2   C
2   D
3   X
3   X
3   Z
4   Y
4   Y
5   M
6   N
7   O
8   U
8   T
8   U

并期望输出

CustID  Rating  ID
1   A   1
1   A   1
1   B   1
2   A   1
2   B   2
2   C   3
2   D   4
3   X   1
3   X   1
3   Z   2
4   Y   1
4   Y   1
5   M   1
6   N   1
7   O   1
8   U   1
8   T   2
8   U   1

2 个答案:

答案 0 :(得分:0)

在下面的解决方案中,我将不同的可能的等级选择为要在数组语句中使用的宏变量。然后,在等级列中搜索这些不同的值,以返回每次成功找到时分配的编号。

在这种情况下,您可以通过将%sysfunc替换为3(不同等级的数量,如果您事先知道的话)来避免使用该宏语句。但是%sysfunc语句可以在您不知道的情况下帮助解决此问题。

data have;
  input CustomerID    Rating $;
  cards;
  1           A       
  1           A       
  1           B       
  2           A       
  2           A       
  3           A       
  3           A       
  3           B       
  3           C     
  ;
run; 

proc sql noprint;
 select distinct quote(strip(rating)) into :list separated by ' '
 from have
 order by 1;
 %put &list.;
quit;

如果您事先知道电话号码:

data want;
  set have;
  array num(3) $ _temporary_ (&list.);
  do i = 1 to dim(num);
    if findw(rating,num(i),'tips')>0 then id = i;
  end;
    drop i;
 run; 

否则:

%macro Y;
data want;
  set have;
  array num(%sysfunc(countw(&list., %str( )))) $ _temporary_ (&list.);
  do i = 1 to dim(num);
    if findw(rating,num(i),'tips')>0 then id = i;
  end;
    drop i;
 run; 
%mend;
%Y;

输出:

Obs CustomerID Rating id 
1    1          A      1 
2    1          A      1 
3    1          B      2 
4    2          A      1 
5    2          A      1 
6    3          A      1 
7    3          A      1 
8    3          B      2 
9    3          C      3 

答案 1 :(得分:0)

假定数据按客户ID和等级排序(与原始未编辑的问题相同)。以下是您想要的:

data want;
   set have;
   by customerid rating;

   if first.customerid then
      id = 0;

   if first.rating then
      id + 1;
run;