使用MAX并返回具有最大列值的整行

时间:2011-06-29 11:39:29

标签: tsql sql-server-2008

我是SQL的新手,并且正在努力为我的MAX情况找到一个可行的解决方案。

我目前有一张表格如下:

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

我想要的结果很简单:

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

由于日期不明确,我不能在日期使用MAX和GROUP BY。

3 个答案:

答案 0 :(得分:10)

您可以使用row_number,例如:

select  *
from    (
        select  row_number() OVER(partition by id order by version desc) as rn
        ,       *
        from    YourTable
        ) as SubQueryAlias
where   rn = 1

答案 1 :(得分:8)

这应该做的工作:

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

答案 2 :(得分:1)

对于具有窗口函数的SQL-Server版本:

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