[英]SQL to get the closest date
我有这个查询,它给了我最近的日期但不正确,它只有一种方式
select *
from Table1
where id = 80
and startdate = (select top 1 startdate
from Table1
where id = 80
order by abs(convert(float, getdate() - StartDate)))
我想确保如果有较大的日期和较小的日期与所选日期的差异最小,它应该选择该记录。
知道我在这里缺少什么吗?
如果您想要数据类似于id = 80
的startdate
的行,您可以使用以下内容:
select top (3) t1.*
from (select t1.*,
max(case when id = 80 then startdate end) over () as date_80
from Table1 t1
) t1
order by abs(datediff(day, startdate, date_80));
如果你想要一个记录:
select top (1) t1.*
from (select t1.*,
max(case when id = 80 then startdate end) over () as date_80
from Table1 t1
) t1
where id <> 80
order by abs(datediff(day, startdate, date_80))
如果出现像今天 12 月 10 日这样的情况,而您有 12 月 15 日和 12 月 5 日,则按 startdate 降序对最接近的记录进行子排序必须将较晚的日期放在列表的顶部。
我还将使用内置的 function DATEDIFF,将日期视为 FLOAT 是一种具有一些缺点的古老技术,包括可能对天数的一部分产生混淆
select * from Table1 where id = 80
and startdate = (select top 1 startdate from Table1
where id = 80
order by
abs(DATEDIFF(day,getdate(),startdate)) ASC, --use a built in function over FLOAT
StartDate DESC) --If there are equidistant dates, this will take the higher of those dates
我想您只需要在查询中添加startdate<>t1.startdate
如下所示。 缺少它可能导致与 output 相同的开始日期
select * from Table1 t1
where id = 80
and startdate = (select top 1
startdate from Table1
where id = 80 and startdate<>t1.
startdate order by
abs(convert(float,getdate() -
StartDate)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.