Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JOIN question

Status
Not open for further replies.

JontyMC

Programmer
Nov 26, 2001
1,276
GB
I have two tables I want to join, but I only want the top row of the second table, ie:

table1:
col1 col2
aaaa bbbb
cccc dddd

table2:
col3 col4
aaaa eeee
aaaa ffff

Desired result:
col1 col2 col4
aaaa bbbb eeee
cccc dddd null

At the moment I have

SELECT * FROM table1 t1
LEFT JOIN table2 t2
ON t1.col1 = t2.col3

But I get:
col1 col2 col4
aaaa bbbb eeee
aaaa bbbb ffff
cccc dddd null

How can I adjust the query?

Jon

"I don't regret this, but I both rue and lament it.
 
create table #table1 (col1 varchar(10), col2 varchar(10))
insert into #table1
values ('aaaa','bbbb')
insert into #table1
values ('cccc','dddd')


create table #table2 (col3 varchar(10), col4 varchar(10))
insert into #table2
values ('aaaa','eeee')
insert into #table2
values ('aaaa','ffff')


select col1,col2,col4 from #table1 t1 left join(
select col3,min(col4) col4 from #table2
group by col3) t2
ON t1.col1 = t2.col3

Denis The SQL Menace
SQL blog:
Personal Blog:
 
In reality, my table 2 has several columns. I can't use min() on each column, because I that might get data from different rows.

Jon

"I don't regret this, but I both rue and lament it.
 
I worked it out myself:

SELECT * FROM table1 t1
LEFT JOIN table2 t2
ON t1.col1 = t2.col3
WHERE t2.col4 = (SELECT MIN(col4) FROM table2 WHERE col3 = t2.col3)

Jon

"I don't regret this, but I both rue and lament it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top