我在SQL Server中有一个表。
ID PID LASTMODIFIED REASON
1 1 01/01/2011 XYZ
2 1 04/01/2011 XYY
3 2 05/01/2011 ZZZ
4 2 03/01/2011 ABC
我想为每个PID选择基于MAX(LASTMODIFIED)的行。对于EX,select应返回以下内容:
ID PID LASTMODIFIED REASON
2 1 04/01/2011 XYY
3 2 05/01/2011 ZZZ
Pelase帮我解决了SQL语句。谢谢。
答案 0 :(得分:4)
SELECT A.ID, A.PID, A.LastModified, A.Reason
FROM MyTable AS A INNER JOIN (
SELECT PID, MAX(LastModified) AS MaxDate
FROM MyTable
GROUP BY PID) AS B ON A.PID = B.PID AND A.LastModified = B.MaxDate