I have two tables: Company, Event.
Company
{
id,
name
}
Event
{
id,
id_company,
date,
name
}
It’s one to many relation.
I want to have results of companies (every company only once) with the latest event.
I’m using postgres. I have this query:
select distinct on (COM.id)
COM.id,
COM.name,
EVT.date,
EVT.name
FROM Company COM
LEFT JOIN Event EVT on EVT.id_company = COM.id
ORDER BY COM.id, EVT.date DESC
It looks good but I’m wondering if I could have the same result using subqueries or something else instead of distinct and order by date of the event.
2
Answers
You can use row_number and then select row number 1, like below:
You could use rank() to achieve your results using a subquery or CTE such as this one.
View on DB Fiddle