如何在SQL中获得日期行差异

时间:2019-04-26 11:04:00

标签: mysql

我下面有一张这样的桌子

表1

id  date    
--------------------
12  20-04-2019 12:35
2   20-04-2019 12:55
11  20-04-2019 11:57
7   20-04-2019 12:00
5   20-04-2019 12:05

我想变得像下面

id  date                diff
----------------------------------------
12  20-04-2019 12:35    0
2   20-04-2019 12:55    20-04-2019 00:20
11  20-04-2019 11:57    20-04-2019 00:20
7   20-04-2019 12:00    20-04-2019 00:03
5   20-04-2019 12:05    20-04-2019 00:05

请帮助我。

1 个答案:

答案 0 :(得分:1)

请找到包含您的方案的示例数据的演示:

DECLARE @TestTable TABLE (Id INT, DateValue DATETIME)

INSERT INTO @TestTable (Id, DateValue) VALUES
(12 , '04-20-2019 12:35'),
(2  , '04-20-2019 12:55'),
(11 , '04-20-2019 11:57'),
(7  , '04-20-2019 12:00'),
(5  , '04-20-2019 12:05');

SELECT Id, 
       DateValue,
       CONVERT(VARCHAR(5), DATEADD(minute, DATEDIFF(MINUTE, LAG(DateValue) OVER (ORDER BY (SELECT NULL)), DateValue), 0), 114) AS Diff
FROM @TestTable;

输出:

Id  DateValue                 Diff
------------------------------------
12  2019-04-20 12:35:00.000   NULL
2   2019-04-20 12:55:00.000   00:20
11  2019-04-20 11:57:00.000   23:02
7   2019-04-20 12:00:00.000   00:03
5   2019-04-20 12:05:00.000   00:05