如何在SQL Server查询中找到最近的时间?

4
id     Bus arrival time
1          6:30
2          7:00
3          9:00
4          10:00
5          15:00
6          16:00

如果一辆公交车在6:40到达,那么最近的时间应该是6:30

如果公交车在9:35到达,最近的时间应该是10:00,我需要使用T-SQL查询来解决这个问题。

谢谢您提前的帮助, 安尼尔


1
你是如何存储“公交到站时间”数据的?你使用了什么数据类型? - Dai
2个回答

4
declare @checkTime time = '6:40'

select top 1 * from schedule
order by ABS(DATEDIFF(Second, @checkTime, busArrivalTime))  

SQLFIDDLE


0
您可以这样做:
DECLARE @TIME TIME = '6:45'


DECLARE @TEMP TABLE(ID int,start time);

insert into @temp values(1, '6:30')
insert into @temp values(1, '7:00')
insert into @temp values(1, '9:00')
insert into @temp values(1, '10:00')
insert into @temp values(1, '15:00')
insert into @temp values(1, '6:30')
insert into @temp values(1, '16:00')


SELECT top(1)start ,ABS(DATEDIFF(MINUTE , @TIME ,START )) as diff
FROM @TEMP
order by diff

这个查询对您有帮助吗? - Hiren Dhaduk
这里有个提示:将@TIME设置为8:45并进行测试。 - iruvar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接