DATE_ADD or DATE_DIFF error when grouping dates in BigQuery

帅比萌擦擦* 提交于 2019-12-13 20:24:13

问题


Try and search as I might, I still cannot figure this out and although https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#date_add has assisted a bit, I am still stuck. I am trying to group dates into weeks but keep getting either one of the two errors below the code.

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

The desirable outcome would be the date at the start of the week (could be Monday or Sunday, whichever)

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

This seems to be a common question but most of the answers are for T-SQL and not standard SQL. My date column is type Date but that is the return type so that should not be a problem.

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)

I am getting a Unrecognized name: week at [2:10] error with the above code or Error: Expected INTERVAL expression at [2:29] if I change the date_expression in the DATE_ADD function to, say, DATE "2009-01-01"


回答1:


Below is for BigQuery Standard 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   

If to apply to sample data in your question as in below example

#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   

output will be

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


来源:https://stackoverflow.com/questions/57347965/date-add-or-date-diff-error-when-grouping-dates-in-bigquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!