【问题标题】:BigQuery - DATE_TRUNC errorBigQuery - DATE_TRUNC 错误
【发布时间】:2018-03-20 10:32:47
【问题描述】:

试图从旧表中获取每月汇总数据。意思是日期列是字符串:

amount  date_create
100     2018-01-05
200     2018-02-03
300     2018-01-22

但是,命令

 Select DATE_TRUNC(DATE date_create, MONTH) as month, 
        sum(amount) as amount_m 
 from table  
 group by 1

返回以下错误:

错误:语法错误:应为“)”但得到标识符“date_create”

为什么这个查询没有运行,可以做些什么来避免这个问题?

谢谢

【问题讨论】:

    标签: date google-bigquery bigquery-standard-sql


    【解决方案1】:

    看起来您打算在那里转换 date_create 而不是使用 DATE 关键字(这是您构造文字值的方式)。试试这个:

    Select DATE_TRUNC(DATE(date_create), MONTH) as month, 
        sum(amount) as amount_m 
    from table
    GROUP BY 1
    

    【讨论】:

    • 这个返回Error: No matching signature for function DATE for argument types: STRING. Supported signatures: DATE(TIMESTAMP, [STRING]); DATE(DATETIME); DATE(INT64, INT64, INT64) 但是,铸造工作:date_trunc(cast(date_create as date), MONTH) as Month 工作
    【解决方案2】:

    我想通了:

    date_trunc(cast(date_create as date), MONTH) as Month

    【讨论】:

      【解决方案3】:

      BigQuery 标准 SQL 的另一个选项 - 使用 PARSE_DATE 函数

      #standardSQL
      WITH `project.dataset.table` AS (
        SELECT 100 amount, '2018-01-05' date_create UNION ALL
        SELECT 200, '2018-02-03' UNION ALL
        SELECT 300, '2018-01-22' 
      )
      SELECT 
        DATE_TRUNC(PARSE_DATE('%Y-%m-%d', date_create), MONTH) AS month, 
        SUM(amount) AS amount_m 
      FROM `project.dataset.table`  
      GROUP BY 1  
      

      结果为

      Row month       amount_m     
      1   2018-01-01  400  
      2   2018-02-01  200  
      

      在实践中 - 我更喜欢 PARSE_DATE 而不是 CAST 作为对数据格式的前一种文档期望

      【讨论】:

        【解决方案4】:

        尝试在 date_creat 中添加双引号:

        Select DATE_TRUNC('date_create', MONTH) as month, 
                sum(amount) as amount_m 
         from table  
         group by 1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-20
          • 2018-10-06
          • 2015-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多