根据另一列的MIN()和MAX()值创建计算字段,按唯一ID分组



我有一个这样的表,其中包含关于对象位置和存在时间长度的信息(年龄(:

Date        ID  Age x   y
2021-03-25  20  1   531 295
2021-03-25  20  2   478 272
2021-03-25  20  3   421 272
2021-03-26  20  1   478 286
2021-03-26  21  1   903 342

我试图选择某个ID的x位置,当该ID的年龄处于其最小值时(名为xStart的列(,当它处于其最大值时(名名为xFin的列(。ID表示每天不同的对象,因此25日的ID 20将与26日的ID不同。

我希望得到的表格看起来像这样:

Date           ID  Age x   y   xStart xEnd
2021-03-25     20  1   531 295 531    421
2021-03-25     20  2   478 272 531    421
2021-03-25     20  3   421 272 531    421
2021-03-26     20  1   478 286 478    some number
2021-03-26     21  1   903 342 908    some other number

该表可以针对每个ID进行分组:

Date         ID  MAX(Age) xStart xEnd
2021-03-25   20  3        531    421
2021-03-26   20  1        478    some number
2021-03-26   21  1        908    some other number

如果我理解,您可以使用窗口函数:

select distinct date, id,
max(age) over (partition by date, id),
first_value(x) over (partition by date, id order by age) as xstart,
first_value(x) over (partition by date, id order by age desc) as xend
from t;

最新更新