我在sqlbq中有一个表,其中包含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
1条答案
按热度按时间kpbpu0081#
LAG()
是从上一行获取值的正确函数。你只需要使用TIMESTAMP_DIFF()
正确地:请注意,看起来您希望
id
. 如果是这样,你应该PARTITION BY
也: