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 查询

提前致谢, 阿尼尔

4

2 回答 2

4
declare @checkTime time = '6:40'

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

SQLFIDDLE

于 2013-07-06T05:06:14.067 回答
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
于 2013-07-06T04:57:21.753 回答