如何在每个组中获取上面行的最大值(Sql 或 SAS)
How to get max of the rows above in each group(Sql or SAS)
数据:
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
非常感谢!:)
如果您的数据库支持窗口聚合则
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
如果您想了解行顺序,那么 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;
您需要一个累积最大值:
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
。
数据:
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
非常感谢!:)
如果您的数据库支持窗口聚合则
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
如果您想了解行顺序,那么 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;
您需要一个累积最大值:
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
。