如何在 BigQuery 中获取连续时间戳之间的差异
Posted
技术标签:
【中文标题】如何在 BigQuery 中获取连续时间戳之间的差异【英文标题】:How to Get Difference Between Consecutive TimeStamps in BigQuery 【发布时间】:2016-07-26 19:39:51 【问题描述】:我有一张如下所示的表格:
ID DateTime
1 5-1-16 12:25:13
1 5-1-16 12:28:46
2 5-1-16 12:25:18
2 5-1-16 12:29:34
我想找出每个 ID 的每个连续时间戳之间的秒数差异。有没有办法在 BigQuery 中做到这一点?我有几千条记录。我知道我需要先将时间与日期隔离开来。
【问题讨论】:
【参考方案1】:下面试试
SELECT
ID,
TIMESTAMP_TO_SEC(TIMESTAMP(DateTime))-TIMESTAMP_TO_SEC(TIMESTAMP(prev_DateTime)) AS diff,
FROM (
SELECT
ID,
DateTime,
LAG(DateTime) OVER(PARTITION BY ID ORDER BY DateTime) AS prev_DateTime
FROM
(SELECT 1 AS ID, '2016-05-01 12:25:13' AS DateTime),
(SELECT 1 AS ID, '2016-05-01 12:28:46' AS DateTime),
(SELECT 2 AS ID, '2016-05-01 12:25:18' AS DateTime),
(SELECT 2 AS ID, '2016-05-01 12:29:34' AS DateTime)
)
添加
SELECT
ID,
TIMESTAMP_TO_SEC(TIMESTAMP(DateTime))-TIMESTAMP_TO_SEC(TIMESTAMP(prev_DateTime)) AS diff,
FROM (
SELECT
ID,
DateTime,
LAG(DateTime) OVER(PARTITION BY ID ORDER BY DateTime) AS prev_DateTime
FROM YourTable
)
我注意到 - 您的 DateTime 字段的格式似乎不寻常 - '5-1-16 12:29:34' 如果在实施上述查询时这对您来说是个问题 - 您可以尝试以下一个 请注意:对于此查询,您需要enable Standard SQL
SELECT
ID,
UNIX_SECONDS(DateTime) - UNIX_SECONDS(prev_DateTime) AS diff
FROM (
SELECT
ID,
DateTime,
LAG(DateTime) OVER(PARTITION BY ID ORDER BY DateTime) AS prev_DateTime
FROM (
SELECT
ID,
PARSE_TIMESTAMP("%m-%d-%y %H:%M:%S", DateTime) AS DateTime
FROM YourTable
)
)
【讨论】:
感谢您的回复。但是,我有几千个 ID 和日期时间,如何在不输入每个 ID 和日期时间的情况下修改此查询? 在 FROM 后面使用你的表名。这几个选择被用作你的例子:o) 见补充回答以上是关于如何在 BigQuery 中获取连续时间戳之间的差异的主要内容,如果未能解决你的问题,请参考以下文章