作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个看起来像这样的表:
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/
我是一名优秀的程序员,十分优秀!