每个连续行之间的时间戳差异bigquery sql

5jvtdoz2  于 2021-08-01  发布在  Java
关注(0)|答案(1)|浏览(521)

我在sqlbq中有一个表,其中包含id和datetime(timestamp)列。我想计算每个连续行之间的时间戳差,比如说秒,并用计算出的时间差创建一个新列。
表格:

  1. ID DateTime
  2. a 2019-10-15 10:00:19 UTC
  3. a 2019-10-15 10:00:29 UTC
  4. a 2019-10-15 10:00:39 UTC
  5. a 2019-10-15 10:00:49 UTC
  6. a 2019-10-15 10:00:59 UTC
  7. the desired result would look like this:
  8. ID DateTime TimeDiff
  9. a 2019-10-15 10:00:19 UTC null
  10. a 2019-10-15 10:00:29 UTC 10
  11. a 2019-10-15 10:00:39 UTC 10
  12. a 2019-10-15 10:00:49 UTC 10
  13. a 2019-10-15 10:00:59 UTC 10

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

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

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

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

kpbpu0081#

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

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

请注意,看起来您希望 id . 如果是这样,你应该 PARTITION BY 也:

  1. timestamp_diff(DateTime,
  2. lag(DateTime, 1) OVER (PARTITION BY id ORDER BY DateTime),
  3. second
  4. ) as TimeDiff

相关问题