Reputation: 83
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.
Upvotes: 8
Views: 10363
Reputation: 238058
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
Upvotes: 12
Reputation: 115510
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
Upvotes: 3
Reputation: 11359
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
Upvotes: 10