Bigquery: Group timestamp by month

Viewed 6799
3 Answers

It sounds like you want the TIMESTAMP_TRUNC function, e.g.

select TIMESTAMP_TRUNC(event_timestamp, MONTH) as timestamp1
FROM `alive-ios.analytics_160092165.events_201810*`
GROUP BY timestamp1

Below is for BigQuery Standard SQL

SELECT 
  FORMAT_TIMESTAMP('%Y-%m', TIMESTAMP_MICROS(event_timestamp)) month, 
  COUNT(1) events
FROM `project.dataset.table`
GROUP BY month 

Note: most likely you want to count events for each month, so I added COUNT(1), but you can add whatever you need - like SUM(amount) for example if you want to calculate some metric named value

Also, your wildcard expression is build in such a way that it will have only events for month of October 2018 (assuming the table name represent time of event) - so you will need to relax a little you wildcard expression to (for example) alive-ios.analytics_160092165.events_2018* so you will have events for months of whole 2018 year

Above assuming your event_timestamp is represented in microseconds
If in reality they are of TIMESTAMP type - just remove use of TIMESTAMP_MICROS() function

Building on Elliott's example, I think you need to convert the value to a timestamp first. From your example data I think you need TIMESTAMP_MICROS

TIMESTAMP_MICROS

select TIMESTAMP_TRUNC(TIMESTAMP_MICROS(event_timestamp), MONTH) as timestamp1
FROM `alive-ios.analytics_160092165.events_201810*`
GROUP BY timestamp1
Related