我在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
答案 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 ║
╚════╩══════╩═════════════════════════╝