对于每个 ID,获取 Product 不为空的第一条记录 (Postgresql)

For each ID get the first record where Product is not null (Postgresql)

我有客户数据,其中包含约会发生时的信息、约会类型以及是否选择了产品。 我正在尝试为 Product 不为 null 的每个 id 获取最早的约会。基本上减少 table 其中 id 只出现一次与约会日期和类型不丢失产品。

这似乎没有满足我的需求。它选择所有条目的最小日期:

select id, min("appointment date"), "appointment type", Product
from product
order by 1,2;

这是我的数据:

在 Postgres 中,这可以使用 distinct on ()

来完成
select distinct on (p.id) p.id, p.appointment_date, p.appointment_type, p.product
from product p
where p.product is not null
order by p.id, p.appointment_date;