3

试图从 Legacy 表中获取每月汇总数据。含义日期列是字符串:

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”

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

谢谢

4

4 回答 4

3

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

Select DATE_TRUNC(DATE(date_create), MONTH) as month, 
    sum(amount) as amount_m 
from table
GROUP BY 1
于 2018-03-20T11:45:25.800 回答
1

我想到了:

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

于 2018-03-21T19:36:56.810 回答
1

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

于 2018-03-21T21:28:02.297 回答
0

尝试将双引号添加到 date_creat :

Select DATE_TRUNC('date_create', MONTH) as month, 
        sum(amount) as amount_m 
 from table  
 group by 1
于 2018-03-20T10:37:40.590 回答