如何获得每组中最多的行(Sql或SAS)

时间:2016-10-19 01:54:47

标签: sql sas max teradata

数据:

ID   step order 
100  1    1
100  2    2
100  3    3
100  1    4
200  2    5
200  3    6
200  1    7

期望的结果(我想获得每组中上面的最大行数)

ID   step  max_step
100  1     1
100  2     2
100  3     3
100  1     3
200  2     2
200  3     3
200  1     3

非常感谢!:)

3 个答案:

答案 0 :(得分:1)

如果您的数据库支持窗口聚合,那么

SELECT id,
       step,
       Max(step) OVER( partition BY ID ORDER BY "order") as max_step
From yourtable

如果您希望从上面的行中获得最大步数而不考虑ID,请删除partition by

SELECT id,
       step,
       Max(step) OVER(ORDER BY "order") as max_step
From yourtable

答案 1 :(得分:0)

如果你想对行顺序有所了解,那么SAS将是更简单的答案。

data want;
  set have;
  by ID;
  retain max_step;
  if first.id then call missing(max_step);
  max_step = max(step,max_step);
run;

答案 2 :(得分:0)

您需要累积最大值

max(step)
over(partition by id
     order by ordercol
     rows unbounded preceding)

由于Teradata不遵循默认为range unbounded preceding的标准SQL,您需要添加它(无论如何都是这样)。

只有last_value默认为累积

last_value(step)
over(partition by id
     order by ordercol)

当然,您也可以添加rows unbounded preceding

相关问题