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)
 Join to the latest values in a table

Author  Topic 

yonabout
Posting Yak Master

112 Posts

Posted - 2007-02-28 : 08:12:07
Hi,

Sometimes I need to retrieve values from a table where they match the max() value from a different table.

In this example, I'm getting the max version number from #process, then joining it back on itself to get the processIDs that I need. I'm then joining this to the #items table to return the results I want

The method I use is fine, but I just wondered if there's a better / simpler / more efficient way of doing it.

-- prepare sample data
create table #Process (ProcessID int, ProcessName char(20), version int)
create table #Items (ItemID int, ProcessID int, ItemName char(20))

insert #Process
select 101, 'Process1', 1 union all
select 102, 'Process2', 1 union all
select 103, 'Process3', 1 union all
select 104, 'Process1', 2 union all
select 105, 'Process1', 3

insert #Items
select 900, 101, 'Item1' union all
select 901, 101, 'Item2' union all
select 902, 102, 'Item3' union all
select 903, 103, 'Item4' union all
select 904, 101, 'Item5' union all
select 905, 102, 'Item6' union all
select 906, 103, 'Item7' union all
select 907, 104, 'Item8' union all
select 908, 103, 'Item9' union all
select 909, 102, 'Item10' union all
select 910, 103, 'Item11' union all
select 911, 105, 'Item12' union all
select 912, 105, 'Item13'

select itemid, itemname from #items
inner join

--get the latest process info
(select
processid
from
#Process
inner join
(select
processname,
max(version) as version
from #process
group by processname) as maxvalues
on #Process.processname = maxvalues.processname
and #Process.version = maxvalues.version) as latestprocesses

on #items.processid = latestprocesses.processid

drop table #process
drop table #items




Cheers,

Yonabout

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-02-28 : 08:33:09
If using SQL Server 2005, this might be easier to read
SELECT		i.ItemID,
i.ItemName
FROM #Items AS i
INNER JOIN (
SELECT ProcessID,
ROW_NUMBER() OVER (PARTITION BY ProcessName ORDER BY Version DESC) AS RecID
FROM #Process
) AS x ON x.ProcessID = i.ProcessID
WHERE x.RecID = 1


Peter Larsson
Helsingborg, Sweden
Go to Top of Page

yonabout
Posting Yak Master

112 Posts

Posted - 2007-02-28 : 08:34:59
We're not due to move to 2005 for another year or so.

Basically I just wanted an opinion of whether what I was doing was OK or rubbish.


Cheers,

Yonabout
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-02-28 : 08:47:57
It's ok!


Peter Larsson
Helsingborg, Sweden
Go to Top of Page

yonabout
Posting Yak Master

112 Posts

Posted - 2007-02-28 : 08:52:06
OK,

Thanks for the peer review!

Cheers,

Yonabout
Go to Top of Page
   

- Advertisement -