我的SQL Server表如下所示
Id Date Msg
1 01-01-2015 A
1 02-01-2015 B
2 03-01-2015 C
我想写一个查询来获得结果如下
Id Date Msg
1 02-01-2015 B
2 03-01-2015 C
我正在尝试
SELECT Id,Max(Date) , Msg
Group By Id, Msg
这也是我的第一行。我希望Msg for Max date为特定ID。
任何建议请
答案 0 :(得分:2)
使用Window Function
SELECT Id,
Date,
Msg
FROM (SELECT *,
Row_number()OVER (partition BY Id ORDER BY [Date] DESC ) rn
FROM tablename) a
WHERE rn = 1
另一种方法是在date
中找到每Id
个subquery
,然后在主表中找到join
结果。试试这个。
SELECT Id,
Date,
Msg
FROM tablename a
JOIN (SELECT Id,
Max([Date])[Date]
FROM tablename
GROUP BY Id) B
ON a.Id = b.id
AND a.[Date] = b.[Date]
答案 1 :(得分:0)
在where子句
中获取最大日期行的简单方法这是简单的示例查询;
SELECT * FROM TABLE T1
WHERE T1.TIME = (SELECT MAX(TIME) FROM TABLE WHERE ID = T1.ID )