Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 One-To-Many relationship causing multiple returns

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-08-05 : 08:16:20
Doug writes "Here Goes:

Group Table PK = Group_Id
Company Table PK = Company_Id
Size Table PK = Size_Id

Group record contains a Company_Id field
Size record contains a Company_Id field

A Group can only belong to one Company, but a Company can have several Groups.
A Size record can only have one Company reference, but a Company can have several Size Records

Our goal: Select all Group records, bring in any available Company records, and bring in only the highest Size record based on its End_Date field.

The Problem: When we do normal joins (typically Left), we get multiple records coming back as a result of the one-to-many relationship between Company and Size. We need to select specific fields from each table, and have tried the Max function, Top X, etc. Help!

BTW, SQL Server V7, Windows NT 4"

r937
Posting Yak Master

112 Posts

Posted - 2002-08-05 : 11:57:46
assuming each Group always has a Company, we can use INNER JOIN

assuming Company may not have any Size, we will use LEFT JOIN

join the Company to the Size row with the max End_Date for that Company, using a correlated subselect

select G.Group_id, G.otherstuff
, C.Company_id, C.otherstuff
, S.Size_id, S.otherstuff
from GroupTable G
inner
join CompanyTable C
on G.Company_id = C.Company_id
left
join SizeTable S
on C.Company_id = S.Company_id
where S.End_Date =
( select max(End_Date)
from SizeTable
where Company_id = C.Company_id )

if Size is missing for a given Company, those columns will be null

p.s. "Group" as a table name might get you in trouble -- it's a reserved word



rudy
http://rudy.ca/
Go to Top of Page
   

- Advertisement -