T-SQL-获取最近的日期和最近的将来日期

| 假设下面的记录表
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
我想按人检索最近的约会日期。所以我需要一个查询,将给出以下结果集。
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)
谢谢!     
已邀请:
        假设您所说的“最近”是指“最近”,例如“存储日期”是距当前日期最少的几天,我们不在乎它是在当前日期之前还是之后。当前日期”,则应该这样做(可能需要进行简单的调试):
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
它使用SQL 2005及更高版本中的row_number()函数。子查询根据规格“订购”数据,主查询则选择最合适的数据。 另请注意: 搜索基于当前日期 我们只是在计算以天,时(小时,分钟等)为单位的时差 如果两天是等距的(例如,之前2天,之后2天),我们随机选择1天 所有这些都可以根据您的最终要求进行调整。     
        (Phillip击败了我,窗口功能是一个很好的选择。这是另一种方法:) 假设我正确理解您的要求是获取最接近当前日期的日期(无论是过去还是将来),请考虑以下查询:
SELECT t.Name, t.AppointmentDate
FROM
(
    SELECT Name, AppointmentDate, ABS(DATEDIFF(d, GETDATE(), AppointmentDate)) AS Distance
    FROM Table
) t
JOIN
(
    SELECT Name, MIN(ABS(DATEDIFF(d, GETDATE(), AppointmentDate))) AS MinDistance
    FROM Table
    GROUP BY Name
) d ON t.Name = d.Name AND t.Distance = d.MinDistance
    

要回复问题请先登录注册