假设下面的记录表
ID Name AppointmentDate
-- -------- ---------------
1 Bob 1/1/2010
1 Bob 5/1/2010
2 Henry 5/1/2010
2 Henry 8/1/2011
3 John 8/1/2011
3 John 12/1/2011
Run Code Online (Sandbox Code Playgroud)
我想按人检索最近的约会日期.所以我需要一个查询,它将提供以下结果集.
1 Bob 5/1/2010 (5/1/2010 is most recent)
2 Henry 8/1/2011 (8/1/2011 is most recent)
3 John 8/1/2011 (has 2 future dates but 8/1/2011 is most recent)
Run Code Online (Sandbox Code Playgroud)
谢谢!
假设你说"最近"的地方你的意思是"最接近",就像"存储的日期是距离当前日期最少的日子而我们不关心它是在当前日期之前还是之后",那么这应该这样做(可能需要进行简单的调试):
SELECT ID, Name, AppointmentDate
from (select
ID
,Name
,AppointmentDate
,row_number() over (partition by ID order by abs(datediff(dd, AppointmentDate, getdate()))) Ranking
from MyTable) xx
where Ranking = 1
Run Code Online (Sandbox Code Playgroud)
这使用了SQL 2005及更高版本的row_number()函数.子查询按照规范"排序"数据,主查询选择最合适的数据.
还要注意:
所有这些都可以根据您的最终要求进行调整.