T-SQL - Getting most recent date and most recent future date(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 - 获取最近的日期和最近的未来日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:T-SQL - 获取最近的日期和最近的未来日期
基础教程推荐
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 在多列上分布任意行 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
