在组中选择MAX Value及其标识密钥

时间:2014-10-13 15:34:32

标签: sql sql-server select

我在SQL Server中有一个表:

Id    Type     Date  
--------------------------------------
1     80       2014-00-00 00:00:00.000
2     80       2013-00-00 00:00:00.000
3     81       2012-00-00 00:00:00.000
4     81       2011-00-00 00:00:00.000
5     81       2010-00-00 00:00:00.000

我想获取其他类型的最大日期记录,如下所示,如何查询?

非常感谢

Id    Type     Date  
--------------------------------------
1     80       2014-00-00 00:00:00.000
3     81       2012-00-00 00:00:00.000

1 个答案:

答案 0 :(得分:0)

;WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY [Type] ORDER BY [Date] DESC)
    FROM YourTable
)
SELECT  ID,
        [Type],
        [Date]
FROM CTE
WHERE RN = 1;

Here is a sqlfiddle及其演示。

结果是:

╔════╦══════╦═════════════════════════╗
║ Id ║ Type ║          Date           ║
╠════╬══════╬═════════════════════════╣
║  1 ║   80 ║ 2014-00-00 00:00:00.000 ║
║  3 ║   81 ║ 2012-00-00 00:00:00.000 ║
╚════╩══════╩═════════════════════════╝