Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return one row from a left outer join

Tags:

sql

oracle11g

I have the following that works fine:

SELECT mcr.mat_change_req_id, mcr.line_item_number
    , r.remarks, r.remarks_date
FROM mat_change_req mcr
    left outer join mat_change_req_remarks r ON mcr.mat_change_req_id = r.mat_change_req_id
WHERE mcr.contract_id = 'IR-30910'
    AND
    mcr.project_number = '0801082'

The problem is that table mat_change_req_remarks (r) has a many-to-one relationship with mat_change_req (mcr) and therefore if r has multiple rows, the above query returns a row for each multiple in r.
I would like to only return ONE row from r if there are multiples where MIN(r.remarks_date). r.remarks_date is a date field.

Thanks in advance!

like image 357
indianapolymath Avatar asked Dec 20 '22 13:12

indianapolymath


1 Answers

Something like this:

SELECT mcr.mat_change_req_id, 
       mcr.line_item_number, 
       r.remarks, 
       r.remarks_date
FROM mat_change_req mcr
    left outer join (
      select mat_change_req_id, 
             remarks,
             remarks_date,
             row_number() over (partition by mat_change_req_id order by remarks_date) as rn
      from mat_change_req_remarks
    ) r ON mcr.mat_change_req_id = r.mat_change_req_id and r.rn = 1
WHERE mcr.contract_id = 'IR-30910'
  AND mcr.project_number = '0801082'
like image 178
a_horse_with_no_name Avatar answered Jan 05 '23 05:01

a_horse_with_no_name