每个连续行之间的时间戳差异BIGQUERY SQL

时间:2020-07-01 11:15:18

标签: sql google-bigquery

我在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

1 个答案:

答案 0 :(得分: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;

请注意,您似乎每个id都需要这个 。如果是这样,您也应该PARTITION BY

       timestamp_diff(DateTime,
                      lag(DateTime, 1) OVER (PARTITION BY id ORDER BY DateTime), 
                      second
                     ) as TimeDiff
相关问题