开发者

Using MAX and returning whole row with max column value

开发者 https://www.devze.com 2023-03-16 08:18 出处:网络
I am new to SQL and struggling with finding a working solution for my MAX situation. I currently have a table that looks like:

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
开发者_Go百科

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.


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号