dbTalk Databases Forums  

Simple (?) SQL problem

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss Simple (?) SQL problem in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Aviast
 
Posts: n/a

Default Simple (?) SQL problem - 07-31-2010 , 07:38 AM






G'day,

I've got a feeling this is a dead-simple problem and I'm going to be
embarrassed by the answer, but here goes...

I have a table "tblDocumentVersion" which has these fields:
* "VersionID" which is the primary key
* "DocID" which is a foreign key pointing to tblDocument
* "Version" which is a textual representation of a version (not
always numerical in this case)

I want the DocID and VersionID of the highest Version of each
document.

So far I've got this:

SELECT DocID, max(Version) FROM tblDocumentVersion GROUP BY DocID;

But I just can't figure out how to add the corresponding VersionID
into the query. If I add it to the "GROUP BY" clause then I get
*every* version, not just the max().

OK, embarrass me

Reply With Quote
  #2  
Old   
Gert-Jan Strik
 
Posts: n/a

Default Re: Simple (?) SQL problem - 07-31-2010 , 07:57 AM






I don't think there is a solution that will embarrass you.

Try this:

SELECT DocID, Version, VersionID
FROM (
SELECT DocID, Version, VersionID
, ROW_NUMBER() OVER (PARTITION BY DocID ORDER BY Version DESC) AS rn
FROM tblDocumentVersion
) T
WHERE rn=1

--
Gert-Jan

Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.