[英]Timestamp difference between every consecutive row BIGQUERY SQL
我在 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
LAG()
是正确的 function 从上一行获取值。 您只需要正确使用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;
请注意,您似乎需要每个id
。 如果是这样,您也应该PARTITION BY
:
timestamp_diff(DateTime,
lag(DateTime, 1) OVER (PARTITION BY id ORDER BY DateTime),
second
) as TimeDiff
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.