gpt4 book ai didi

sql - 如何在 BigQuery 中获取连续时间戳之间的差异

转载 作者:行者123 更新时间:2023-12-04 13:43:13 28 4
gpt4 key购买 nike

我有一个看起来像这样的表:

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 中执行此操作?我有几千条记录。我知道我需要先将时间与日期分开。

最佳答案

试试下面

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)
)

added

 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
)
)

关于sql - 如何在 BigQuery 中获取连续时间戳之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38598551/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com