Skip to content

Instantly share code, notes, and snippets.

@glamp
Created December 16, 2013 23:40
Show Gist options
  • Save glamp/7997085 to your computer and use it in GitHub Desktop.
Save glamp/7997085 to your computer and use it in GitHub Desktop.
Generate a table of all reasonable dates in Postgres
drop table if exists dim_date;
with recursive date_creator as(
select cast('20060101' as date) as date_value, 1 as key, 0 as mod_key
union all
select date_value + 1, key + 1,
case when mod(key,7) = 0 then mod_key+1 else mod_key end
from date_creator where date_value + 1 <= '20900101'
)
select
key
,date_value::date as date
,extract(day from date_value) as day
,extract(month from date_value) as month
,extract(year from date_value) as year
,case
when extract(dow from date_value) = 0 then 'sunday'
when extract(dow from date_value) = 1 then 'monday'
when extract(dow from date_value) = 2 then 'tuesday'
when extract(dow from date_value) = 3 then 'wednesday'
when extract(dow from date_value) = 4 then 'thursday'
when extract(dow from date_value) = 5 then 'friday'
when extract(dow from date_value) = 6 then 'saturday'
when extract(dow from date_value) = 7 then 'sunday'
end as day_of_week
,case
when to_char(date_value, 'MM') = '01' then 'january'
when to_char(date_value, 'MM') = '02' then 'february'
when to_char(date_value, 'MM') = '03' then 'march'
when to_char(date_value, 'MM') = '04' then 'april'
when to_char(date_value, 'MM') = '05' then 'may'
when to_char(date_value, 'MM') = '06' then 'june'
when to_char(date_value, 'MM') = '07' then 'july'
when to_char(date_value, 'MM') = '08' then 'august'
when to_char(date_value, 'MM') = '09' then 'september'
when to_char(date_value, 'MM') = '10' then 'october'
when to_char(date_value, 'MM') = '11' then 'november'
when to_char(date_value, 'MM') = '12' then 'december'
end as month_name
,case
when to_char(date_value, 'MM') IN ('01','02','03') then 'Q1'
when to_char(date_value, 'MM') IN ('04','05','06') then 'Q2'
when to_char(date_value, 'MM') IN ('07','08','09') then 'Q3'
when to_char(date_value, 'MM') IN ('10','11','12') then 'Q1'
end as quarter
,mod_key
into
dim_date
from
date_creator
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment