【问题标题】:Query that accounts for changes in the hour of a timestamp说明时间戳小时变化的查询
【发布时间】:2021-11-25 22:50:14
【问题描述】:

问题如下。我有一个包含以下列的表:

machine timestamp speed (meters/minute)
C1 22/9/2020, 16:45 15
C1 22/9/2020, 16:55 5
C1 22/9/2020, 17:20 19

我想知道的是每台机器每小时行进的距离,所以我需要从下一行的时间戳中减去当前行的时间戳,然后乘以第一行的速度(例如:16:55 - 16:45 = 10 分钟 -> 10 * 15 = 16:45 和 16:55 之间的 150 米)。

我能够通过使用类似于以下逻辑的逻辑来做到这一点(这不是完全相同的查询):

 ' 1st get the timestamp of the next row'
 lead(query."timestamp") OVER (PARTITION BY query.id ORDER BY query."timestamp") AS lead_timestamp
 ' 2nd get the duration'
 query."lead_timestamp" - query."timestamp" AS duration
 ' 3rd calculate the distance'
 query."duration" * query."speed" AS distance
 ' 4th group by hour'
 GROUP BY date_trunc('hour', CAST(query."timestamp" AS timestamp)

它几乎可以 100% 正常工作。我得到一张类似于下面的表格:

machine timestamp duration (meters)
C1 22/9/2020, 16:00 275
C1 22/9/2020, 17:00 ...

但是正如您所看到的,当我每小时对数据进行分组时,16:00 小时的总米数不正确,因为在时间戳之后没有时间戳等于“22/9/2020, 16:55 ” 这迫使分组在“22/9/2020, 16:59”结束。因此,最后,我将 17:00 小时的持续时间部分添加到 16:00 小时(这 20 分钟已添加到 16:00 小时)。

我不知道如何解决这个问题,但我已经研究了 UNION 以在时间戳之间有小时转换时添加一个“人工”行,甚至在开始减去值来计算持续时间之前。但这似乎相当复杂,因为我必须为每台机器做这件事,而且我不知道它会有多少行。

你能帮帮我吗?谢谢!如果我不清楚,请询问更多信息!

【问题讨论】:

  • 请提供更多信息。 (因为你不清楚)尝试添加“预期输出”。还尝试给出 COMPLETE SQL 语句(您生成的语句缺少SELECT,以及最后的)
  • 另外,MySQL 不知道函数date_trunc() ....

标签: mysql sql timestamp


【解决方案1】:

这可能会有所帮助:

WITH cte as (
   select 'c1' as  machine, '2020-09-22 16:46' as timestamp, 15 as speed
   union all 
   select 'c1', '2020-09-22 16:56', 5
   union all 
   select 'c1', '2020-09-22 17:20', 19)
select 
   machine,
   timestamp,
   speed,
   lead(timestamp) over (partition by machine) nextTime,
   TIMEDIFF( lead(timestamp) over (partition by machine), timestamp) diffTime,
   minute(TIMEDIFF( lead(timestamp) over (partition by machine), timestamp))*speed meters
from cte;

输出:

machine timestamp speed nextTime diffTime meters
c1 2020-09-22 16:46 15 2020-09-22 16:56 00:10:00.000000 150
c1 2020-09-22 16:56 5 2020-09-22 17:20 00:24:00.000000 120
c1 2020-09-22 17:20 19

【讨论】:

    猜你喜欢
    • 2016-09-12
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2018-10-22
    • 1970-01-01
    • 2018-10-09
    • 2015-02-09
    相关资源
    最近更新 更多