简体   繁体   中英

oracle sql select where value is lowest from a different column

I have written a SQL query for oracle and I'd like to select the records that have the lowest value of each group of another value that i'm querying. What I've written seems to work, but I don't feel confident that it is actually correct.

select cam.visible_id campaign_id, 
  ps.visible_id plate_set_id,
  ps.alias plate_set_name,
  ps.date_created date_created,
  count(distinct(iw.isolate_id)) number_of_clones
from plate_set ps
join campaign cam on cam.id = ps.campaign_id
join plate_plate_set pps on pps.plate_set_id = ps.id
join plate p on p.id = pps.plate_id
join plate_type pt on pt.id = p.plate_type_id
join isolate_well iw on iw.plate_id = p.id
where pt.label='Master Plate'
and ps.date_created = (select min(ps2.date_created) from plate_set ps2 where ps2.campaign_id = cam.id)
group by cam.visible_id, ps.alias, ps.visible_id, ps.date_created
order by cam.visible_id

;

I don't understand how my query even works in the where clause here:

and ps.date_created = (select min(ps2.date_created) 
from plate_set ps2 
where ps2.campaign_id = cam.id)

In my mind, ps.date_created should be a join where ps.date_created = the first plate set created in every campaign

something like

join (
select min(plate_set.date_created) as created_date
 from plate_set 
join campaign on plate_set.campaign_id 
group by campaign.id 
) helperTable on helperTable.NotSureHowToJoinLikeThis on ps.date_created

is what I have actually correct and sql queries the campaign ids then filters on the row with the lowest date created or can someone help me with the join I should do to write it better?

I would suggest you rewrite the where clause into a joined subquery.

...
from plate_set ps
inner join campaign cam on cam.id = ps.campaign_id
inner join plate_plate_set pps on pps.plate_set_id = ps.id
inner join plate p on p.id = pps.plate_id
inner join plate_type pt on pt.id = p.plate_type_id
inner join isolate_well iw on iw.plate_id = p.id
inner join (select min(date_created) mdc, campaign_id from plate_set group by campaign_id) ps2 on  ps2.campaign_id = cam.id
and ps.date_created = ps2.mdc
where pt.label='Master Plate'
...

In you where clause the subquery will be executed for every row you are comparing with. While as a join, the query would run one time for the whole dataset, so (depending on your data and other factors) this might give you a performance pump

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM