【问题标题】:Time difference between two times in the same table同一张表的两次时间差
【发布时间】:2009-08-25 10:19:36
【问题描述】:

(请注意,我最近在 StackOverflow 上看到了类似的问题,但是我在任何地方都找不到 - 如果有人能找到,请发布链接)

我有一个表,其中有一个日期时间字段。例如:

表格数据

DateTime date;
int number;

我需要找出一行中的日期和下一行中的日期之间的差异。我试过查询:

select date as current_date, date - (select top 1 date where date > current_date from data) as time_difference from date

但是这不起作用,因为“current_date”。有没有一种方法可以用一个查询来做到这一点?

【问题讨论】:

  • 如何定义下一行?
  • 下一行是表格中最接近较大日期的行。

标签: sql sql-server datetime


【解决方案1】:
SELECT  date AS current_date, next_date - date AS difference
FROM    mytable mo
CROSS APPLY
        (
        SELECT  TOP 1 date AS next_date
        FROM    mytable mi
        WHERE   mi.date > mo.date
        ORDER BY
                date
        ) q

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多