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

T-SQL - Getting most recent date and most recent future date(T-SQL - 获取最近的日期和最近的未来日期)
本文介绍了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

我想按人检索最近的约会日期.所以我需要一个查询来提供以下结果集.

I want to retrieve the most recent appointment date by person. So I need a query that will give the following result set.

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)

谢谢!

推荐答案

假设您说最近"的意思是最近",例如存储的日期是距当前日期最少的天数,而我们不这样做"不关心它是在当前日期之前还是之后",那么应该这样做(可能需要进行琐碎的调试):

Assuming that where you say "most recent" you mean "closest", as in "stored date is the fewest days away from the current date and we don't care if it's before or after the current date", then this should do it (trivial debugging might be required):

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() 函数.子查询根据规范对数据进行排序",主查询选择最合适的.

This usese the row_number() function from SQL 2005 and up. The subquery "orders" the data as per the specifications, and the main query picks the best fit.

还要注意:

  • 搜索基于当前日期
  • 我们只计算天数差异,忽略时间(小时、分钟等)
  • 如果两天是等距的(比如之前 2 天和之后 2 天),我们随机选择一个

所有这些都可以根据您的最终要求进行调整.

All of which could be adjusted based on your final requirements.

这篇关于T-SQL - 获取最近的日期和最近的未来日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)