【问题标题】:How to find specific holiday date that varies by year in BigQuery?如何在 BigQuery 中查找因年份而异的特定假期日期?
【发布时间】:2022-12-07 07:40:57
【问题描述】:

我正在尝试查询劳动节前一周的日期。劳动节是每年九月第一个星期一的美国联邦假日。我正在尝试选择劳动节和劳动节前的整周。我有点接近这种查询

select * from `bigquery-public-data.ghcn_d.ghcnd_1991` 

where extract(month from date) = 9 
and extract(dayofweek from date) = 2  
and extract(week from date) = 36

但并不总是第 36 周,有时是第 35 周(所以上面的查询是错误的)。

我猜我必须做一个日期减法才能得到劳动节前的整周......但现在我只需要帮助找到如何查询每个九月的第一个星期一。

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    这是一种方法:

    select    t.*
    from      `bigquery-public-data.ghcn_d.ghcnd_1991` t
         join (
                select    format_date('%Y%m',date) as yr_mo,
                          date_sub(min(date), interval 1 week)  as week_before,
                          min(date) as first_monday
                from      `bigquery-public-data.ghcn_d.ghcnd_1991`   v
                where     extract(dayofweek from date) = 2 
                      and extract(month from date) = 9
                group by  format_date('%Y%m',date)
              ) v
           on t.date between v.week_before and v.first_monday;
    

    这假定您想要表格中日期为劳动节或劳动节前一周内的所有行。

    【讨论】:

      【解决方案2】:

      因为它是 9 月的第一个星期一,您可以在 CTE 或子查询中执行 MIN 日期,以获取劳动节和前一周:

      WITH labor_day as (
        select MIN(date) date
        from `bigquery-public-data.ghcn_d.ghcnd_1991` 
        where extract(month from date) = 9 
        and extract(dayofweek from date) = 2  
      )
      
      SELECT distinct ghcnd.date
      FROM `bigquery-public-data.ghcn_d.ghcnd_1991` ghcnd
      INNER JOIN labor_day 
       on ghcnd.date between labor_day.date-7 and labor_day.date
      

      【讨论】:

        【解决方案3】:

        您可以在 BigQuery 表中包含每年的所有假期日期,然后进行简单的连接以了解某个日期是否为公共假期。

        我创建了一个开放源代码的 BigQuery 函数,任何人都可以从他们的 BigQuery 项目中调用它:

        只需致电 --> select bigfunctions.eu.is_public_holiday(date('2022-07-14'), 'FR') --> 它将返回true

        https://unytics.io/bigfunctions/reference/#is_public_holiday

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-19
          相关资源
          最近更新 更多