1

我有一列包含日期,并想介绍另一列,它是关于日期是否是其各自季度的最后一天的标志 (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

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

4

1 回答 1

1

使用计算代替 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
于 2021-07-27T16:56:35.517 回答