【问题标题】:How to retrieve first and last day of the previous month in Google BigQuery?如何在 Google BigQuery 中检索上个月的第一天和最后一天?
【发布时间】:2021-08-20 16:51:42
【问题描述】:

我希望创建一个获取上个月的第一个和最后一个日期,以便可以使用 between 语句执行 WHERE 子句。它看起来像这样

WHERE 
FirstSold_Date BETWEEN first_day_previous_month AND last_day_previous_month 

【问题讨论】:

    标签: sql date google-bigquery datediff


    【解决方案1】:

    试试这个:

    WHERE FirstSold_Date BETWEEN date_trunc(date_sub(current_date(), interval 1 month), month) AND last_day(date_sub(current_date(), interval 1 month), month)
    

    【讨论】:

      【解决方案2】:

      我不会为此推荐between。而是:

      WHERE FirstSold_Date >= date_add(date_trunc(current_date, month), interval -1 month) and
            FirstSold_Date < date_trunc(current_date, month)
      

      这种方法的优点是相同的逻辑也适用于timestamps 和datetimes。查看最后日期会在涉及时间时产生问题。

      【讨论】:

        【解决方案3】:

        考虑下面

        where date_trunc(FirstSold_Date, month) = date_trunc(date_sub(current_date, interval 1 month), month) 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-07
          • 1970-01-01
          • 1970-01-01
          • 2015-02-06
          • 1970-01-01
          • 2015-04-03
          • 2013-11-25
          • 2015-07-09
          相关资源
          最近更新 更多