计算组内最大值对应记录
【问题】
Proc SQL Group By Question
Hello All,
I hope you can help me on this. In my dataset I have siblings and their addresses. I am trying to group all siblings by address, so I know all the siblings who reside at an address. Now in this group I only want to pick the youngest sibling and get that information. I am trying to do this in EG, I have the dataset sorted by mailing address, but I would like to know is there a way where I can get the youngest sibling in the group. (something like select top 1)
Here is my dataset
Address name age
111 street1 child1 5
111 street1 child2 10
In this group I only want to output info for
child1
别人的回答:
proc sql noprint;
create table want as
select *
from have
group by Address
having age eq min(age);
【回答】
上面给出的 SQL 其实不正确,这个问题的难点是 min 函数只能计算出最小值,但不能取出“最小值对应的记录”,再加上分组和关联,就会让问题更显复杂。其实也可以用 keep/ top/row_number,或者用窗口函数等方法,当然,这些方法都比较麻烦。
这个问题结合 SPL 就简单多了,SPL 中的 top 函数可以取出最大值对应的记录,比如 salary.top(3;amount) 取出 amount 最小的三条记录,salary.top(-1;amount) 取出 amount 最大的那条记录。下面的这句代码可以解决你的所有问题:
A |
|
1 |
简单解释一下:
T1: T1 表
.group(Address):按 Address 对 T1 分组
.(~.top(1;age)):继续计算,对每组数据,取出 age 最小的记录。
.union(): 将各组数据合并。
集算器是结构化计算开发工具,和 JAVA 或报表工具很容易集成,可以参考:【Java 如何调用 SPL 脚本】