Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
Discussion Groups
Database Servers
DB2InformixIngresMS SQLOraclePervasive.SQLPostgreSQLProgressSybase
Desktop Databases
FileMakerFoxProMS AccessParadox
General
General DB TopicsDatabase Theory
Related Topics
Java Development.NET DevelopmentVB DevelopmentMore Topics ...

Database Forum / DB2 Topics / July 2004

Tip: Looking for answers? Try searching our database.

JOINS

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Terry - 30 Jul 2004 19:00 GMT
Hi All,

This is a simple problem I expect, but I cant seem to crack it.

I have to tables I wish to join A & B. I wish to join them where A.a =
B.a. There are multiple entries for B.a, and I wish to join to the
rows with the lowest B.b.

SELECT
A.a
MIN(B.b)
FROM
A
LEFT JOIN B
ON (A.a = B.a)
GROUP BY
A.a

That works fine but I also want to extract the other columns from B on
the row that is matched

i.e.
A    B
.a    .a    .b    .c
1         1      5    8
2    1      8    2
    2      7    9
    2      1    7

So I want to obtain

A.a       B.a      B.b     B.c
1         1         5       8
2         2         1       7

An alternative is to use the WHERE instead of the JOIN

SELECT
A.a
B.b
B.c
MIN(B.b)
FROM
A
,B
WHERE
A.a = B.a
AND B.c = (SELECT MIN(B.c) FROM B WHERE A.a = B.a)

But in some instance there is no match at all in B, and 'where' will
lost the A information. Additionally I have a number of row from B  I
need to return;B.d, B.e etc.

Any suggestions

Thanks

Terry
Knut Stolze - 30 Jul 2004 20:07 GMT
> Hi All,
>
[quoted text clipped - 3 lines]
> B.a. There are multiple entries for B.a, and I wish to join to the
> rows with the lowest B.b.

SELECT ...
FROM   A JOIN ( SELECT ...
               FROM   B
               WHERE  b <= ALL ( SELECT b
                                 FROM   B ) ) AS B ON
         ( A.a = B.a )

> But in some instance there is no match at all in B, and 'where' will
> lost the A information. Additionally I have a number of row from B  I
> need to return;B.d, B.e etc.

Then you need an OUTER JOIN - either LEFT OUTER JOIN or RIGHT OUTER JOIN (I
always mix up in which table the rows are preserved if there are no
matching rows in the other table).

Signature

Knut Stolze
Information Integration
IBM Germany / University of Jena

 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.