【问题标题】:Check if date is equal to last day of its respective quarter检查日期是否等于其各自季度的最后一天
【发布时间】:2021-10-03 09:35:41
【问题描述】:

我有一列包含日期,并想介绍另一列,它是一个标志 (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

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

【问题讨论】:

    标签: sql date hive hiveql quarter


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      相关资源
      最近更新 更多