MySQL中每一行的日期差异

时间:2019-03-16 12:52:17

标签: mysql mysql-8.0

我希望每个日期时间行的秒数差异。如何在mysql中实现呢?

id record
1 2019-02-12 19:59:44
2 2019-02-12 20:00:27
3 2019-02-12 20:01:10

所需的输出:

id record               difference in seconds
1  2019-02-12 19:59:44  0
2  2019-02-12 20:00:27  43
3  2019-02-12 20:01:10  44

1 个答案:

答案 0 :(得分:2)

我认为最简单的方法是将其转换为可以直接计算的UNIX_TIMESTAMP()

您可以直接在当前记录和LAG()之间进行计算。

column - LAG(column) OVER()
column + LAG(column) OVER()

查询

SELECT 
   t.id
 , t.record
 , (
     CASE 
       WHEN 
          UNIX_TIMESTAMP(t.record) - UNIX_TIMESTAMP(LAG(t.record) OVER(ORDER BY t.record ASC)) IS NOT NULL 
       THEN 
          UNIX_TIMESTAMP(t.record) - UNIX_TIMESTAMP(LAG(t.record) OVER(ORDER BY t.record ASC))
       ELSE 0
     END
   ) AS difference_in_seconds                                                                      
FROM 
 t
ORDER BY 
  t.id ASC

结果

| id  | record              | difference_in_seconds |
| --- | ------------------- | --------------------- |
| 1   | 2019-02-12 19:59:44 | 0                     |
| 2   | 2019-02-12 20:00:27 | 43                    |
| 3   | 2019-02-12 20:01:10 | 43                    |

请参阅demo

  

为什么要在CASE表达式中重复自己?使用COALESCE

确实

COALESCE(
       UNIX_TIMESTAMP(t.record) - UNIX_TIMESTAMP(LAG(t.record) OVER(ORDER BY t.record ASC))
     , 0                                                                  
   ) AS difference_in_seconds  

与使用

相同
 (
     CASE 
       WHEN 
          UNIX_TIMESTAMP(t.record) - UNIX_TIMESTAMP(LAG(t.record) OVER(ORDER BY t.record ASC)) IS NOT NULL 
       THEN 
          UNIX_TIMESTAMP(t.record) - UNIX_TIMESTAMP(LAG(t.record) OVER(ORDER BY t.record ASC))
       ELSE 0
     END
   ) AS difference_in_seconds