如何在SQL中创建季度(会计年度)临时表

时间:2019-06-21 14:17:54

标签: sql hive

我正在处理一个跨越3年的大型医疗索赔数据集(在Hive中)。我想根据某一列值date_service

将每年分成几个季度

这大致就是我所做的:

create table user.temp_quarterly as
select *, 
    CASE WHEN date_service between '2015-10-01' and '2015-12-31' THEN 'Q1 2016'
    WHEN date_service between '2016-01-01' and '2016-03-31' THEN 'Q2 2016'
    WHEN date_service between '2016-04-01' and '2016-06-30' THEN 'Q3 2016'
    WHEN date_service between '2016-07-01' and '2016-09-30' THEN 'Q4 2016'

    WHEN date_service between '2016-10-01' and '2016-12-31' THEN 'Q1 2017'
    WHEN date_service between '2017-01-01' and '2017-03-31' THEN 'Q2 2017'
    WHEN date_service between '2017-04-01' and '2017-06-30' THEN 'Q3 2017'
    WHEN date_service between '2017-07-01' and '2017-09-30' THEN 'Q4 2017'

    WHEN date_service between '2017-10-01' and '2017-12-31' THEN 'Q1 2018'
    WHEN date_service between '2018-01-01' and '2018-03-31' THEN 'Q2 2018'
    WHEN date_service between '2018-04-01' and '2018-06-30' THEN 'Q3 2018'
    WHEN date_service between '2018-07-01' and '2018-09-30' THEN 'Q4 2018'

    ELSE null END AS Quarter
from user.temp_medicalclaims

这是正确的方法还是有更有效的方法解决此问题?

1 个答案:

答案 0 :(得分:0)

我认为这样做更简单:

select ('Q' || quarter(add_months(date_service, 3)) || 'Q' ||
        year(add_months(date_service, 3))
       ) as yyyyq

也就是说,添加三个月,然后使用内置函数来表示年份和季度。