【问题标题】:DATE_ADD or DATE_DIFF error when grouping dates in BigQuery在 BigQuery 中对日期进行分组时出现 DATE_ADD 或 DATE_DIFF 错误
【发布时间】:2019-08-04 15:43:56
【问题描述】:

尽我所能尝试搜索,我仍然无法弄清楚这一点,尽管https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#date_add 提供了一些帮助,但我仍然卡住了。我正在尝试将日期分组为几周,但不断收到代码下方的两个错误之一。

day         bitcoin_total   dash_total
2009-01-03  1               0
2009-01-09  14              0
2009-01-10  61              0

理想的结果是一周开始的日期(可以是星期一或星期日,以哪个为准)

day         bitcoin_total   dash_total
2008-12-28  1               0
2009-01-04  75              0

这似乎是一个常见问题,但大多数答案都是针对 T-SQL 而不是标准 SQL。我的日期列是 Date 类型,但这是返回类型,所以这应该不是问题。

DATE_ADD(week, DATE_DIFF(week, 0, day), 0) Date
FROM
my_table
GROUP BY
DATE_ADD(week, DATE_DIFF(week, 0, day), 0) 
ORDER BY
DATE_ADD(week, DATE_DIFF(week, 0, day), 0)

如果我将 DATE_ADD 函数中的 date_expression 更改为 DATE "2009-01-01",则上述代码会出现 Unrecognized name: week at [2:10] 错误或 Error: Expected INTERVAL expression at [2:29]

【问题讨论】:

    标签: google-bigquery bigquery-standard-sql


    【解决方案1】:

    以下是 BigQuery 标准 SQL

    #standardSQL
    SELECT DATE_TRUNC(day, WEEK) AS day, 
      SUM(bitcoin_total) AS bitcoin_total, 
      SUM(dash_total) AS dash_total
    FROM `project.dataset.table`
    GROUP BY day   
    

    如果应用到您的问题中的示例数据,如下例所示

    #standardSQL
    WITH `project.dataset.table` AS (
      SELECT DATE '2009-01-03' day, 1 bitcoin_total, 0 dash_total UNION ALL
      SELECT '2009-01-09', 14, 0 UNION ALL
      SELECT '2009-01-10', 61, 0 
    )
    SELECT DATE_TRUNC(day, WEEK) AS day, 
      SUM(bitcoin_total) AS bitcoin_total, 
      SUM(dash_total) AS dash_total
    FROM `project.dataset.table`
    GROUP BY day   
    

    输出将是

    Row day         bitcoin_total   dash_total   
    1   2008-12-28  1               0    
    2   2009-01-04  75              0    
    

    【讨论】:

    • 如果回答有帮助,也考虑投票:o)
    • 我有/我有。感谢您及时的回复。澄清一下,BigQuery 标准 SQL 是它自己的语言吗?
    • 它基于 SQL 2011 标准,具有查询嵌套和重复数据等扩展功能
    • 好的,我正在搜索 SQL 2011 的解决方案,再次感谢。
    猜你喜欢
    • 2023-03-22
    • 2019-01-04
    • 2021-11-03
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2017-03-23
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多