如何根据最小日期的条件选择ID的第一行(跨越或忽略另一列)?

问题描述 投票:0回答:2

我想选择首次购买者以及首次购买的类别的买方。

这里是示例数据:

ID   Category  Buy_date
1    Car       2019-01-01
1    Truck     2019-01-02
1    House     2019-01-03
1    House     2019-01-04

2    Car      2019-01-01
2    Car      2019-01-02
2    Truck    2019-01-03

我的预期结果:

ID   Category    Buy_date
1    Car         2019-01-01
2    Car         2019-01-01

我的代码:

select ID, category, min(buy_date) over (partition by id) from #a group by 1,2

这里是不正确的结果:

ID    Category    Buy_date
1     Car         2019-01-01
1     Truck       2019-01-01
1     House       2019-01-01

2     Car         2019-01-01
2     Truck       2019-01-01
sql postgresql greatest-n-per-group
2个回答
0
投票

尝试一下:

select id, category, buy_date from test as outer_tab where buy_date = (select min(buy_date) from test where id = outer_tab.id);


0
投票

如果要每个id行,则使用distinct on

select distinct on (id) a.*
from a
order by id, buy_date asc;
© www.soinside.com 2019 - 2024. All rights reserved.