1、求自然日、上一自然日、下一自然日、本周初/末、本月初/末、本季初/末、本年初/末、一月/三月/六月/一年前等
select
calendar_day AS CALENDAR_DAY, --'自然日(日期型)'
regexp_replace(calendar_day,'-','') AS CALENDAR_DT, --'自然日(数值型)'
date_add(calendar_day, -1) AS LAST_CALENDAR_DT, --'上一自然日'
date_add(calendar_day, 1) AS NEXT_CALENDAR_DT, --'下一自然日'
date_add(calendar_day,7-cast(default.date_format(calendar_day, 'u') as int)) AS WEEKEND_DT, --'本周末日期'
date_sub(default.add_months(calendar_day, 1), day(calendar_day)) AS MONTHEND_DT, --'本月末日期'
date_sub(default.add_months(to_date(concat(year(calendar_day),'-01-01')), 3*cast(ceil(month(calendar_day)/3) as int)), 1) AS QUARTEND_DT, --'本季末日期'
to_date(concat(year(calendar_day),'-12-31')) AS YEAREND_DT, --'本年末日期'
date_add(calendar_day,1-cast(default.date_format(calendar_day,'u') as int)) AS WEEK_1ST_DT, --'本周初日期'
date_sub(calendar_day,dayofmonth(calendar_day)-1) AS MONTH_1ST_DT, --'本月初日期'
default.add_months(to_date(concat(year(calendar_day),'-01-01')), 3*cast(ceil(month(calendar_day)/3) - 1 as int)) AS QUART_1ST_DT, --'本季初日期'
to_date(concat(year(calendar_day),'-01-01')) AS YEAR_1ST_DT, --'本年初日期'
default.add_months(calendar_day,-1) AS ONE_MONTH_AGO, --'一个月前'
default.add_months(calendar_day,-3) AS THREE_MONTH_AGO, --'三个月前'
default.add_months(calendar_day,-6) AS SIX_MONTH_AGO, --'六个月前'
default.add_months(calendar_day,-12) AS ONE_YEAR_AGO, --'一年前'
default.add_months(calendar_day,-24) AS TWO_YEAR_AGO, --'两年前'
default.add_months(calendar_day,-36) AS THREE_YEAR_AGO, --'三年前'
default.add_months(calendar_day,-60) AS FIVE_YEAR_AGO, --'五年前'
default.add_months(calendar_day,-120) AS TEN_YEAR_AGO --'十年前'
from (select date_add(date '2008-01-01', t1.pos) as calendar_day
from (select posexplode(split(space(datediff(date '2025-12-31', date '2008-01-01')),' '))) t1
)t2
2、日期有几个来源的情况,而且每个来源都要包含所有日历日,如上海、深圳、香港和银行间交易所,方法如下:
select t1.calendar_day, t1.mkt_code as mkt_code, if(isnotnull(t2.mkt_code), '是', '否') as if_trade_dt from
(select
calendar_day,
mkt_code
from tmp_date t1
LATERAL VIEW explode(split('001,003,004',',')) union_mkt_code as mkt_code) t1
left join (
select '001' as mkt_code,
trade_days as calendar_dt from tmp_shanghai_date
union all
select '003' as mkt_code,
trade_days as calendar_dt from tmp_hongkong_date
union all
select '004' as mkt_code,
trade_days as calendar_dt from tmp_bank_date) t2
on t1.calendar_dt = t2.calendar_dt
and t1.mkt_code = t2.mkt_code