【发布时间】: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