2014-02-22 46 views
1

如何找到SAS中最大值的记录?我有以下结构的数据集:在SAS中找到最大值的记录

age name 
12 joe 
15 jane 
3 bob 
14 rick 

我想找个“名”的这“年龄”是最大的值(在这个例子 - “简”)。

我尝试这样做:

data max; 
    set ages_data; 
    if age > max_age then do; 
     max_age = age; 
    max_name = name; 
    end; 
    retain max_:; 
    keep max_:; 
run; 

这是基于什么我发现这里: https://communities.sas.com/message/170554

,但它并没有为我工作......我究竟做错了什么?

感谢

回答

3

你的代码是好的 - 但输出的所有记录,我假设你希望只有一个?请尝试以下变化:

这种方法
data max; 
    set ages_data end=lastobs; /* identify last record */ 
    if age > max_age then do; 
     max_age = age; 
     max_name = name; 
    end; 
    retain max_:; 
    keep max_:; 
    if lastobs then output; /* only output last record */ 
run; 

的一个缺点是,它只会输出名称的第一个值,对于给定的最长期限。该年龄可能有多个名称值。下面的方法可以为您的用途更为强劲:

proc sql; 
create table max as 
    select name, age 
    from ages_data 
    where age= (select max(age) from ages_data); 

在情况下,它是有用的 - 这里的datalines来进行测试:

data ages_data; 
infile cards; 
input age name $; 
cards; 
12 joe 
15 jane 
3 bob 
14 rick 
;run; 
+0

谢谢!这正是我需要的 - 完美的作品 –