【问题标题】:Timestamp difference between every consecutive row BIGQUERY SQL每个连续行 BIGQUERY SQL 之间的时间戳差异
【发布时间】:2020-10-21 19:52:33
【问题描述】:

我在 SQL BQ 中有一个带有 ID 和 DateTime (TIMESTAMP) 列的表。我想计算每个连续行之间的时间戳差异,比如说秒数,并创建一个具有计算时间差异的新列。

表:

ID     DateTime
a      2019-10-15 10:00:19 UTC
a      2019-10-15 10:00:29 UTC
a      2019-10-15 10:00:39 UTC
a      2019-10-15 10:00:49 UTC
a      2019-10-15 10:00:59 UTC

the desired result would look like this:

ID     DateTime                    TimeDiff
a      2019-10-15 10:00:19 UTC      null
a      2019-10-15 10:00:29 UTC       10
a      2019-10-15 10:00:39 UTC       10
a      2019-10-15 10:00:49 UTC       10
a      2019-10-15 10:00:59 UTC       10

到目前为止,我已经尝试了这些选项但没有成功:

select ID, DateTime,
(LAG(DateTime) OVER (PARTITION BY ID ORDER BY DateTime ASC) - DateTime) AS TimeDiff
from `xxx.yyy.table` 
order by DateTime

select ID, DateTime,
timestamp_diff(lag(DateTime, 1) OVER (ORDER BY DateTime)) as TimeDiff
from `xxx.yyy.table`
order by DateTime

select ID, DateTime,
LAG(DateTime) OVER (PARTITION BY FieldID ORDER BY DateTime ASC) AS timeDiff
from `xxx.yyy.table` 
order by DateTime

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    LAG() 是从上一行获取值的正确函数。你只需要正确使用TIMESTAMP_DIFF()

    select ID, DateTime,
           timestamp_diff(DateTime,
                          lag(DateTime, 1) OVER (ORDER BY DateTime), 
                          second
                         ) as TimeDiff
    from `xxx.yyy.table`
    order by DateTime;
    

    请注意,您似乎想要这个 per id。如果是这样,你也应该PARTITION BY

           timestamp_diff(DateTime,
                          lag(DateTime, 1) OVER (PARTITION BY id ORDER BY DateTime), 
                          second
                         ) as TimeDiff
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多