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.
| Author |
Topic |
|
Aerathi
Starting Member
14 Posts |
Posted - 2006-05-16 : 11:18:03
|
I'm trying to do an inner join to a table, which sometimes contains multiple records.Table1OrderNo ItemNo12345 112345 2Table2OrderNo ItemNo VendorID12345 1 57812345 1 147512345 2 98154 When I join these tables I need it to just return one record for ItemNo 1, and one record for Itemno 2, etc. I'm not really concerned with which record is pulled from table two, the vendor ID is needed but relatively arbitrary. |
|
|
mmarovic
Aged Yak Warrior
518 Posts |
Posted - 2006-05-16 : 11:29:13
|
| Use group by and min or max or correlated query returning top1 vendorID. |
 |
|
|
RyanRandall
Master Smack Fu Yak Hacker
1074 Posts |
Posted - 2006-05-16 : 12:03:55
|
Hi all,Aerathi - Just in case mmarovic's answer was a little too succinct for you, I decided to write it out...  --datadeclare @Table1 table (OrderNo int, ItemNo int)insert @Table1 select 12345, 1union all select 12345, 2declare @Table2 table (OrderNo int, ItemNo int, VendorID int)insert @Table2 select 12345, 1, 578union all select 12345, 1, 1475union all select 12345, 2, 98154--calculation--maxselect a.OrderNo, a.ItemNo, min(VendorID) as VendorIDfrom @Table1 a inner join @Table2 b on a.OrderNo = b.OrderNo and a.ItemNo = b.ItemNogroup by a.OrderNo, a.ItemNo--or minselect a.OrderNo, a.ItemNo, max(VendorID) as VendorIDfrom @Table1 a inner join @Table2 b on a.OrderNo = b.OrderNo and a.ItemNo = b.ItemNogroup by a.OrderNo, a.ItemNo--or not fussedselect OrderNo, ItemNo, (select top 1 VendorID from @Table2 where OrderNo = a.OrderNo and ItemNo = a.ItemNo) as VendorIDfrom @Table1 a--or randomselect OrderNo, ItemNo, (select top 1 VendorID from @Table2 where OrderNo = a.OrderNo and ItemNo = a.ItemNo order by newid()) as VendorIDfrom @Table1 a Ryan Randallwww.monsoonmalabar.com London-based IT consultancy Solutions are easy. Understanding the problem, now, that's the hard part. |
 |
|
|
Aerathi
Starting Member
14 Posts |
Posted - 2006-05-16 : 14:57:52
|
| Ahh thanks. Very helpful stuff. I kind of had an idea how I should do it but I wasn't quite sure how to implement it. |
 |
|
|
|
|
|
|
|