8

I am new to SQL and struggling with finding a working solution for my MAX situation.

I currently have a table that looks like:

ID   Date         Version
001  2010-11-17   2
001  2010-12-01   3
002  2011-01-11   1
002  2011-05-05   2

My desired result is simply:

ID   Date        Version
001  2010-12-01  3
002  2011-05-05  2

I can't use MAX and GROUP BY on date since Date is not distinct.

3
  • Appologies, realised my question is not very clear. I basically want the rows with the highest version number for each ID. thanks Commented Jun 29, 2011 at 11:44
  • Which SQL Server version are you using? Commented Jun 29, 2011 at 11:49
  • Hi Robert, I'm using SQL server 2008. thanks Commented Jun 29, 2011 at 11:53

3 Answers 3

12

You could use row_number for that, like:

select  *
from    (
        select  row_number() OVER(partition by id order by version desc) as rn
        ,       *
        from    YourTable
        ) as SubQueryAlias
where   rn = 1
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for a nice solution but you should point out that it will only work with newer version of SQL Server.
10

This should do the job:

SELECT     ID,
           Date,
           Version
FROM       YourTable
INNER JOIN 
(
    SELECT    ID,
              Max(Version)
    FROM      YourTable
    GROUP BY  ID
) AS x
ON         YourTable.ID = x.ID
AND        YourTable.Version = x.Version

4 Comments

For very large datasets with large numbers of versions per row, this often is the optimal solution (if properly indexed).
+1 this is fine unless there are duplicate version numbers. But from what OP's written I suppose there'ren't.
I mean thanks to Maximilian! Sorry lost track of the original poster. thanks all :)
In some scenario we have one data (date-time column for exam) for ID and Id is not repeated, so grouping by ID will return all record and we need to return MAX(ID), MAX(date-time column) without grouping by in sub-query to got record ID has Max date-time value.
3

For versions of SQL-Server that have window functions:

SELECT ID, Date, Version
FROM
  ( SELECT ID, Date, Version
         , MAX(Version) OVER(PARTITION BY ID) AS MaxVersion
    FROM yourtable
  ) AS tmp
WHERE Version = MaxVersion

3 Comments

In SQL Server, "Windowed functions can only appear in the SELECT or ORDER BY clauses."
@Andomar: thnx, I should check before posting.
@Andomar: fixed. Not sure but probably your version is faster.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.