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)
 Select Newest Version of Record

Author  Topic 

rdugre
Starting Member

32 Posts

Posted - 2003-11-13 : 17:13:22
I'm sure this is a relatively easy answer, but I'm going blank about how to accomplish this.

I'm looking to query a table that includes an ID and version number for each record and returns only the records with the highest version numbers.

Take the following as an example:

CREATE TABLE #Sample (ID int, Ver int, MyText varchar(10))

INSERT #Sample VALUES (1, 1, 'Zebra 1-1')
INSERT #Sample VALUES (1, 2, 'Apple 1-2')
INSERT #Sample VALUES (1, 3, 'Zebra 1-3')
INSERT #Sample VALUES (2, 1, 'Apple 2-1')
INSERT #Sample VALUES (3, 1, 'Zebra 3-1')
INSERT #Sample VALUES (3, 2, 'Apple 3-2')
INSERT #Sample VALUES (4, 1, 'Zebra 4-1')

-- SELECT STATEMENT HERE

DROP TABLE #Sample


I want to end up with the following:

ID Ver MyText
----------- ----------- ----------
1 3 Zebra 1-3
2 1 Apple 2-1
3 2 Apple 3-2
4 1 Zebra 4-1

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2003-11-13 : 17:16:48
[code]

SELECT t1.ID, t1.Ver, MyText
FROM #Sample t1
INNER JOIN (SELECT ID, MAX(Ver) AS Ver FROM #Sample GROUP BY ID) t2 ON t1.ID = t2.ID AND t1.Ver = t2.Ver
ORDER BY t1.ID

[/code]

To see what I did, run the query in the inner join statement. That gets you two of the columns. You then need to join to this table to get the third column.

Tara
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2003-11-13 : 17:20:39
BTW, thanks for providing the DDL for the table, DML for sample data, and the expected result set!

Tara
Go to Top of Page

rdugre
Starting Member

32 Posts

Posted - 2003-11-13 : 17:24:41
Thanks a bunch, Tara! That's exactly what I needed.
Go to Top of Page
   

- Advertisement -