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

How to select the 1 row of ID based on condition of min date (accrossing or ignoring another columns )?

我想select那些第一次购买的买家和他们第一次购买的类别。

这是示例数据:

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

试试这个:

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

如果你想要每个 id 一行,那么使用 distinct on:

select distinct on (id) a.*
from a
order by id, buy_date asc;