BigQuery - DATE_TRUNC 错误

BigQuery - DATE_TRUNC error

正在尝试从 Legacy table 获取每月汇总数据。含义日期列是字符串:

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

Returns 出现以下错误:

Error: Syntax error: Expected ")" but got identifier "date_create"

为什么这个查询没有 运行 以及如何避免这个问题?

谢谢

尝试为 date_creat 添加双引号:

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

您似乎打算在此处强制转换 date_create 而不是使用 DATE 关键字(这就是您构建文字值的方式)。试试这个:

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

我想通了:

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

BigQuery Standard 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 作为前一种文档对数据格式的期望