Create a time dimension table in pure hive SQL
Without further ado, here is the full SQL to create a table giving you one row per day, with date, year, month, day, day and name of the week, day of the year. If you want the hours as well, look at the bottom of this post.
1 | set hivevar:start_day=2010-01-01; |
Note that I use d as date column because date is a reserved keyword.
The biggest issue is to generate one row per day. The trick here is to use a clever combination of posexplode, split and reapeat. This is what the first CTE does:
1 | -- just 10 days for the example |
We can break it down in a few parts:
1 | select datediff("${end_day}", "${start_day}"); |
Just computes the difference between start and end day in days.
1
2
select repeat(“o”, 9);
– output: ooooooooo
Will output a string with 9 ‘o’. The actual character does not matter at all.
1 | select split("ooooooooo", "o"); |
Creates a hive array of 9 (empty) strings.
1 | select posexplode(split("ooooooooo", "o")); |
– output:
– +——+——+–+
– | pos | val |
– +——+——+–+
– | 0 | |
– | 1 | |
– | 2 | |
– | 3 | |
– | 4 | |
– | 5 | |
– | 6 | |
– | 7 | |
– | 8 | |
– | 9 | |
– +——+——+–+
Actually create a row per array element, with the index (0 to 9) and the value (nothing) of each element.
That was the tricky part, the rest is easy. The first CTE creates a row with each date, adding the array index (in day) to the start_day:
1 | with dates as ( |
– +————-+–+
– | dates.d |
– +————-+–+
– | 2010-01-01 |
– | 2010-01-02 |
– | 2010-01-03 |
– | 2010-01-04 |
– | 2010-01-05 |
– | 2010-01-06 |
– | 2010-01-07 |
– | 2010-01-08 |
– | 2010-01-09 |
– | 2010-01-10 |
– +————-+–+
From there on, you can just create whatever column you feel like. Quarter column? floor(1+ month(d)/4) as quarter. Long name of the week? date_format(d, ‘EEEE’) as dayname_of_week_long.
As a bonus, I give you the same table but with hours added. The principles are exactly the same, with a cartesian join beween dates and hour:
1 | set hivevar:start_day=2010-01-01; |