Search code examples
sqlt-sqlgoogle-bigquery

The last day of the previous month - BigQuery


I'm trying to select rows where a timestamp field, recdate, has a date value up to and inclusive of the last completed day of the month. For example, as this is July 2016, I want all rows with date values up to and inclusive of 31-06-2016. This used to work fine in T-SQL, I'd use the following and assign it to @today and chuck that in my WHERE:

DECLARE @today DATETIME SELECT @today = CONVERT(VARCHAR(25),DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())-0,0)));

I'm struggling in BigQuery though, I can't get DATEDIFF or GETDATE to work, was wondering if anybody had thoughts on this?

best wishes

Dave


Solution

  • October 2020 Update (BigQuery Standard SQL)

    BigQuery now support LAST_DAY function as well as arithmetic operations + and '-' for dates

    So, now you can use below options to get last day of previous month

    #standardSQL
    select 
      date_trunc(current_date(), month) - 1, 
      last_day(date_sub(current_date(), interval 1 month)),
      date_sub(last_day(current_date()), interval 1 month)
    

    with output (having in mind it is October 14 today)

    enter image description here

    me personally - i love the first option as least verbose and straightforward!

    -- ~~~~~~~~~~~~~~~~~~~

    Use below as an example (BigQuery Legacy SQL)

    SELECT DATE(DATE_ADD(CURRENT_DATE() , -DAY(CURRENT_DATE()), "DAY"))
    

    BTW, there are 30 days in June :o) - with exception of Priestley's "The Thirty-First of June"