优雅的方式来计算最近的时间

时间:2012-11-16 01:29:14

标签: sql sql-server sql-server-2005 graphics

我有一个参考时间:

'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

1 个答案:

答案 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));

注意:

  1. datediff(d, -datediff(...模式从日期时间中删除日期部分。
  2. 要处理跨午夜场景,除了reftime+1之外,我们还会测试coltime+1abs(reftime-coltime)
  3. ORDER BY执行所有3种方案的最小差异。