【问题标题】:Time differences between row in google big query谷歌大查询中行之间的时间差异
【发布时间】:2017-01-22 09:29:57
【问题描述】:

我目前正在尝试计算谷歌大查询中的行之间的时间戳差异,附件是我用来测试代码 的示例表。

我正在使用此代码

SELECT 
  A.row,
  A.issue.updated_at,
 (B.issue.updated_at - A.issue.updated_at) AS timedifference
FROM [icxmedia-servers:icx_metrics.gh_zh_data_production] A
INNER JOIN [icxmedia-servers:icx_metrics.gh_zh_data_production] B
  ON B.row = (A.row + 1)
WHERE issue.number==6 and issue.name=="archer"
ORDER BY A.requestid ASC

引用自这个问题Calculate the time difference between of two rows

【问题讨论】:

    标签: mysql syntax google-bigquery datediff


    【解决方案1】:

    而不是JOIN,这是使用分析函数更自然地表达。 analytic functions with standard SQL in BigQuery 的文档解释了分析函数的工作原理以及语法是什么。例如,如果您想在 x 值中获取顺序由列 y 确定的连续差异,您可以这样做:

    WITH T AS (
      SELECT
        x,
        y
      FROM UNNEST([9, 3, 4, 7]) AS x WITH OFFSET y)
    SELECT
      x,
      x - LAG(x) OVER (ORDER BY y) AS x_diff
    FROM T;
    

    请注意,要在 BigQuery 中运行此操作,您需要取消选中“显示选项”下的“使用旧版 SQL”框以启用标准 SQL。 WITH T 子句只是为示例设置一些数据。

    对于您的具体情况,您可能需要如下查询:

    SELECT
      row,
      issue.updated_at,
      issue.updated_at - LAG(issue.updated_at) OVER (ORDER BY issue.updated_at) AS timedifference
    FROM `icxmedia-servers.icx_metrics.gh_zh_data_production`
    WHERE issue.number = 6
      AND issue.name = "archer"
    ORDER BY requestid ASC;
    

    如果您想确定updated_at 的差异,而不是单个问题编号,您也可以使用PARTITION BY 子句。例如:

    SELECT
      row,
      issue.name,
      issue.number,
      issue.updated_at,
      issue.updated_at - LAG(issue.updated_at) OVER (
          PARTITION BY issue.number
          ORDER BY issue.updated_at) AS timedifference
    FROM `icxmedia-servers.icx_metrics.gh_zh_data_production`
    ORDER BY requestid ASC;
    

    【讨论】:

    • 我试图做一些与你的建议相同的事情 - issue.updated_at - LAG(issue.updated_at) OVER (ORDER BY issue.updated_at) AS timedifference - 在我的查询中,但我收到一个错误 - Missing function在解析表达式中。你对它的可能性是否正确?
    • 请创建一个单独的问题,并举例说明您要达到的目标。
    • 我试图获取行之间的差异,但值是整数而不是时间戳。 LAG 功能单独工作正常。但是,如果我尝试执行您建议的减法运算,则会收到警告 - 分析表达式中缺少函数。是具有不同列和值的同一个问题。
    • 请创建一个单独的问题。不要一直在这个评论线程上提问。
    • 我也有同样的问题,但我创建了一个新问题,就像你建议我的那样。 stackoverflow.com/questions/46695274/…
    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 2013-04-15
    • 2020-12-20
    • 2021-12-27
    • 1970-01-01
    • 2018-06-21
    • 2013-07-12
    • 2018-11-07
    相关资源
    最近更新 更多