从数据块 SQL 中的日期查找一个月中的第几周

Finding week of the month from the date in databricks SQL

我正在尝试从数据块 sql

中的日期获取 week_of_the_month

这是我的 SQL:

with date as (
  select EXTRACT(DAY FROM '2017-01-01') as day
)

select case
       when day < 8 then '1'
       when day < 15 then '2'
       when day < 22 then '3'
       else '4'
       end as week_of_month

上面的sql在一些极端情况下失败了。例如2010-03-31,那么week_of_month = 5

如何在数据块 SQL 中找到 week_of_month?

按照你的说法,你还要添加另一个 when 子句

select case
         when day < 8 then '1'
         when day < 15 then '2'
         when day < 22 then '3'
         when day < 29 then '4'   --> new
         else '5'                 --> modified
       end as week_of_month