Samo
Samo

Reputation: 8240

Oracle - With a one to many relationship, select distinct rows based on a min value

This question is the same as In one to many relationship, return distinct rows based on MIN value with the exception that I'd like to see what the answer looks like in other dialects, particularly in Oracle.

Reposting from the original description:

Let's say a patient makes many visits. I want to write a query that returns distinct patient rows based on their earliest visit. For example, consider the following rows.

patients
-------------
id    name
1     Bob
2     Jim
3     Mary

visits
-------------
id    patient_id    visit_date    reference_number
1     1             6/29/14       09f3be26
2     1             7/8/14        34c23a9e
3     2             7/10/14       448dd90a

What I want to see returned by the query is:

id    name    first_visit_date    reference_number
1     Bob     6/29/14             09f3be26
2     Jim     7/10/14             448dd90a

In the other question, using postgresql, the best solution seemed to be to use distinct on, but that is not available in other dialects.

Upvotes: 0

Views: 753

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269563

Typically, one uses row_number():

select id, name, visit_date as first_visit_date, reference_number
from (select v.id, p.name, v.visit_date, v.reference_number,
             row_number() over (partition by p.id order by v.visit_date desc) as seqnum
      from visits v join
           patients p
           on v.patient_id p.id
     ) t
where seqnum = 1;

Upvotes: 3

Related Questions