如何在 PostgreSQL 中找到具有最大日期考虑的唯一列值?

How do I find the unique column value with maximum date consideration in PostgreSQL?

例如

product_id | costhead_id | date
1020209    | 1000105     | 2020-04-01 08:58:15
1020209    | 1000182     | 2021-11-24 11:27:40
1020209    | 1000183     | 2021-12-19 16:19:55
1020210    | 1000105     | 2020-04-01 08:58:15
1020210    | 1000182     | 2021-11-24 11:27:40
1020210    | 1000183     | 2021-12-20 16:19:55

我需要一个唯一的 product_id,最大 date。所需值如下所示

product_id | costhead_id | date
1020209    | 1000183     | 2021-12-19 16:19:55
1020210    | 1000183     | 2021-12-20 16:19:55

您可以使用 distinct on:

select distinct on(product_id) *
from table_name
order by product_id, date desc

Fiddle