Join of two tables and want first row of matching records in second table
Kevin Marshall, May 24, 2012 - 1:46 pm UTC
Thank you. Both options are great. WOW!
The second option may be the better fit as the final solution will involve joins on multiple tables with multiple columns taken from each. Based on this, most of the final solution is working.
A reader, August 11, 2015 - 8:45 pm UTC
in this similar question, how can I avoid writing the two subqueries.
create table g(a int, b varchar2(2), d date) -- a, b and d are together unique;
insert into g values (1, 'ER', to_date('01012005','mmddyyyy');
insert into g values (1, 'ER', to_date('06012005','mmddyyyy');
insert into g values (1, 'ER', to_date('01012015','mmddyyyy');
insert into g values (2, 'PR', to_date('01012005','mmddyyyy');
insert into g values (2, 'PR', to_date('01012015','mmddyyyy');
insert into g values (2, 'PR', to_date('06012015','mmddyyyy');
insert into g values (3, 'FR', to_date('06012015','mmddyyyy');
create table n(a int, b varchar2(2), d date, e varchar2(3), f varchar2(3)) -- a, b and d are unique;
insert into n values(1, 'ER', to_date('01012005','mmddyyyy', 'FSC', 'COL');
insert into n values(1, 'ER', to_date('01012014','mmddyyyy', 'FOO', 'CLL');
insert into n values(1, 'PR', to_date('01012014','mmddyyyy', 'FOI', 'COL');
insert into n values(1, 'PR', to_date('06012014','mmddyyyy', 'FIT', 'CLL');
select g.a, g.b, g.d,
(select n.e from n where n.a = g.a and n.b = g.b and n.d = (select max(n.d) from n where n.a = g.a and n.b = g.b and n.d<=g.d) e,
(select n.f from n where n.a = g.a and n.b = g.b and n.d = (select max(n.d) from n where n.a = g.a and n.b = g.b and n.d<=g.d) f
from g
Awesome
A reader, September 13, 2017 - 5:55 pm UTC
Found this post for my problem and glad I did. I had a view that was joining two tables where there is 1 row in table A and zero to many in table B. Issue was that if table B had 4 rows my view would return 4 duplicate rows and distinct could not be used since to_clob for varchar CASE statements were in use. This example applied to my view was the answer, THANKS TOM!
September 14, 2017 - 3:13 am UTC
That's why we never delete stuff in AskTom :-)
Very Useful
A reader, September 11, 2018 - 2:56 pm UTC
Very Useful solution, worked for me in a similar case.