我有一个参考时间:
'2012-05-01 23:35:00'
我还有几次来自某些表格,其中'yyyy-MM-dd'日期部分无关紧要,但相关的是日期部分与'HH:分钟'
------------------------------
| ID | Time |
| -- |-----------------------|
| 01 | '1900-01-01 13:10:00' |
| 02 | '1900-01-01 07:01:00' |
| 03 | '1900-01-02 00:45:00' |
| 04 | '1900-01-02 18:00:00' |
------------------------------
我正在编写一个函数,它将返回最近时间的行(在上面的示例中,这将是ID 03),但我不喜欢我写的内容。
所以我开始以图形方式观察问题。有没有办法用Atan函数做到这一点?
编辑:我正在使用MSSQL server 2005
答案 0 :(得分:3)
declare @reftime datetime;
set @reftime = '20120501 23:00:00';
select TOP(1) with ties
id, time
from (
select
t.*,
dateadd(d, -datediff(d, 0, @reftime), @reftime) reftime,
dateadd(d, -datediff(d, 0, t.time), t.time) coltime
from tbl t
) x
order by (select min(diff)
from
(select abs(datediff(ms, reftime, coltime))
union all
select abs(datediff(ms, reftime+1, coltime))
union all
select abs(datediff(ms, reftime, coltime+1))) y(diff));
注意:
datediff(d, -datediff(...
模式从日期时间中删除日期部分。reftime+1
之外,我们还会测试coltime+1
和abs(reftime-coltime)
。ORDER BY
执行所有3种方案的最小差异。