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

孤街醉人 提交于 2019-12-10 12:12:58

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/25556749/oracle-with-a-one-to-many-relationship-select-distinct-rows-based-on-a-min-va

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!