Search code examples
sqlpostgresqlnullgreatest-n-per-groupmin

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


I have customer data with information when the appointment took place, what type of appointment it was and wheather a Product was selected. I am trying to get the earliest appointment for every id where Product is not null. Basically reduce the table where id only appears once with appointment date and type where product is not missing.

This doesn't seem to give me what I need. It selects the min date for all entries:

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

That is my data:

enter image description here


Solution

  • In Postgres this can be done using 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;