检查日期是否等于其各自季度的最后一天

Check if date is equal to last day of its respective quarter

我有一个包含日期的列,我想引入另一列,该列是一个标志 (1/0),表示该日期是否是相应季度的最后一天。

数据:

| date       |
|------------|
| 2021-04-10 |
| 2021-05-19 |
| 2021-09-30 |

预期输出:

| date       | is_last_day_of_quarter |
|------------|------------------------|
| 2021-04-10 | 0                      |
| 2021-05-19 | 0                      |
| 2021-09-30 | 1                      |

我想出了以下似乎有效的方法:

select
    date,
    case
        when date = last_day_of_q then 1 else 0
    end as is_last_day_of_quarter

from(
    select
        date,
        case
            when month(date) < 4 then (concat(year(date), '03-31'))
            when month(date) between 4 and 6 then concat((year(date)), '-06-30')
            when month(date) between 7 and 9 then concat((year(date)), '-09-30')
            when month(date) between 10 and 12 then concat((year(date)), '-12-31')
        end as last_day_of_q
        from
            some_table
    ) t

我想知道是否有更好的方法来做到这一点,或者是否可以在不必使用子查询的情况下实现它?

用计算代替CASE的方法:

with mytable as(
select '2021-04-10' as mydate union all
select '2021-05-19' as mydate union all
select '2021-09-30' as mydate
)
select mydate, 
       date_sub( concat(YEAR(mydate),'-',lpad(((INT((MONTH(mydate)-1)/3)+1)*3)+1,2,0),'-01'),1) qtr_last_date,
       case when mydate = date_sub( concat(YEAR(mydate),'-',lpad(((INT((MONTH(mydate)-1)/3)+1)*3)+1,2,0),'-01'),1) then 1 else 0 end as flag
 from mytable

结果:

  mydate         qtr_last_date  flag    
  2021-04-10     2021-06-30      0
  2021-05-19     2021-06-30      0
  2021-09-30     2021-09-30      1

但我喜欢你的季度最后一天计算方法(有问题的 CASE 表达式),因为它更容易阅读和理解。您可以轻松删除子查询:

case
    when date = case
                   when month(date) < 4 then (concat(year(date), '03-31'))
                   when month(date) between 4 and 6 then concat((year(date)), '-06-30')
                   when month(date) between 7 and 9 then concat((year(date)), '-09-30')
                   when month(date) between 10 and 12 then concat((year(date)), '-12-31')
                 end
    then 1 else 0
end as is_last_day_of_quarter