SQL Datediff - 在行之间查找datediff

时间:2011-04-20 10:04:16

标签: sql sql-server tsql datediff

我想使用sql查询数据库,以显示id 1,2,3之间的时间差异等等。基本上它会比较它下面的所有记录的行。任何帮助,将不胜感激。

IDCODE  DATE TIME        DIFFERENCE (MINS)
1      02/03/2011 08:00        0
2      02/03/2011 08:10        10
3      02/03/2011 08:23        13
4       02/03/2011 08:25        2
5       02/03/2011 09:25        60
6       02/03/2011 10:20        55
7       02/03/2011 10:34        14

谢谢!

3 个答案:

答案 0 :(得分:23)

如果使用SQL Server,可以采用以下方法:

DECLARE @Data TABLE (IDCode INTEGER PRIMARY KEY, DateVal DATETIME)
INSERT @Data VALUES (1, '2011-03-02 08:00')
INSERT @Data VALUES (2, '2011-03-02 08:10')
INSERT @Data VALUES (3, '2011-03-02 08:23')
INSERT @Data VALUES (4, '2011-03-02 08:25')
INSERT @Data VALUES (5, '2011-03-02 09:25')
INSERT @Data VALUES (6, '2011-03-02 10:20')
INSERT @Data VALUES (7, '2011-03-02 10:34')

SELECT t1.IDCode, t1.DateVal, ISNULL(DATEDIFF(mi, x.DateVal, t1.DateVal), 0) AS Mins
FROM @Data t1
    OUTER APPLY (
        SELECT TOP 1 DateVal FROM @Data t2 
        WHERE t2.IDCode < t1.IDCode ORDER BY t2.IDCode DESC) x

另一种方法是使用CTE和ROW_NUMBER(),如下所示:

;WITH CTE AS (SELECT ROW_NUMBER() OVER (ORDER BY IDCode) AS RowNo, IDCode, DateVal FROM @Data)

SELECT t1.IDCode, t1.DateVal, ISNULL(DATEDIFF(mi, t2.DateVal, t1.DateVal), 0) AS Mins
FROM CTE t1
    LEFT JOIN CTE t2 ON t1.RowNo = t2.RowNo + 1
ORDER BY t1.IDCode

答案 1 :(得分:12)

标准ANSI SQL解决方案。应该在PostgreSQL,Oracle,DB2和Teradata中工作:

SELECT idcode, 
       date_time, 
       date_time - lag(date_time) over (order by date_time) as difference
FROM your_table

答案 2 :(得分:0)

正如@a_horse_with_no_name 提到的使用滞后()

我想在毫秒内知道差异是什么。

Select idcode,
       datetime,
       Difference = datediff(millisecond, lag(convert(datetime2,datetime)) over (order by convert(datetime2,datetime)),convert(datetime2,datetime))
From your_table

就我而言,我需要将字符串转换为 datetime2