Search code examples
sqlgoogle-bigquerybigdata

Best way to break down by weeks in BigQuery


So what I'm looking to do is create a report that shows how many sales a company had on a weekly basis.

So we have a time field called created that looks like this:

2016-04-06 20:58:06 UTC

This field represents when the sale takes place.

Now lets say I wanted to create a report that gives you how many sales you had on a weekly basis. So the above example will fall into something like Week of 2016-04-03 (it doesn't have to exactly say that, I'm just going for the simplest way to do this)

Anyone have any advice? I imagine it involves using the UTEC_TO_xxxxxx functions.


Solution

  • you can use WEEK() function - it gives you week number

    SELECT WEEK('2016-04-06 20:58:06 UTC')
    

    if you need first day of the week - you can try something like

    STRFTIME_UTC_USEC((UTC_USEC_TO_WEEK(TIMESTAMP_TO_USEC(TIMESTAMP('2016-05-02 20:58:06 UTC')), 0)),'%Y-%m-%d')