hive生成日期维度表Hql

hive生成日期维度表

利用现有的函数,生成维度表

表结构

日期key
具体日期
第几月份
第几季度
年份
周几
当前周的第几天
当前月的第几天
当前年的第几天
当前年的第几周
当前周的第一天
当前周的最后一天

分析

上述的表字段都是基于某个具体日期上计算的,所有首先要生成一个日期表,然后再计算每一天的具体属性

范围根据自己的需求,比如我这里定义的日期范围是2022-01-01~2022-12-31

# 1.使用date_add()以及posexplode()生成目标日期范围数据
select date_add("2022-01-01", a.pos) as range_date
from (
   select posexplode(split(repeat("@", datediff("2022-12-31", "2022-01-01")), "@"))
     ) a
#2.计算每一天的属性
with date_range as (
    select date_add("2022-01-01", a.pos) as d
from (
   select posexplode(split(repeat("@", datediff("2022-12-31", "2022-01-01")), "@"))
     ) a
)
select
    date_format(d, 'yyyyMMdd') as date_key
     ,d as `date`
     ,date_format(d,'yyyMM') as month
     ,month(d) as month_short
     ,quarter(d) as quarter
     ,year(d) as year
     ,date_format(d,'EEEE') as zhouji
     ,date_format(d, 'u') as daynumber_of_week
     ,day(d) as daynumer_of_month
     ,date_format(d, 'D') as daynumber_of_year
     ,weekofyear(d) as year_weeks
     ,date_add(d,1 - case when dayofweek(d) = 1 then 7 else dayofweek(d) - 1 end) as week_first_day
     ,date_add(d,7 - case when dayofweek(d) = 1 then 7 else dayofweek(d) - 1 end) as week_last_day
from date_range;

补充几个一个关于date_format的用法

-- 当前日期是周几
select date_format(`current_date`(),'EEE'); 

-- 当前日期是本周第几天
select date_format(`current_date`(),'u');

-- 当前日期是当前年的第几天
select date_format(`current_date`(),'D');
-- 当前日期是当前月份的第几天
select day(`current_date`())

你可能感兴趣的:(hive,big,data,hql,sql)