使用SQL脚本填充时间维度 - Teradata

时间:2017-04-07 11:17:46

标签: sql teradata

伙计,

我正在尝试使用SQL脚本填充时间维度表。

预期输出如下所示。

enter image description here

&安培;下面是部分SQL脚本,它没有给出正确的输出。

SEL   calendar_date AS DATE_,
      RANK( ) OVER ( ORDER BY calendar_date) AS Date_Key,
      RANK( ) OVER ( ORDER BY EXTRACT(MONTH FROM CALENDAR_DATE)) AS Month_Key
FROM  SYS_CALENDAR.CALENDAR 
ORDER BY calendar_Date

你能帮我在我的代码中找到问题吗?

由于代码停留在Month_Key人口,我没有完成剩余的代码......

2 个答案:

答案 0 :(得分:1)

当你sys_calendar.calendar

时,我不明白这一点
select      calendar_date

           ,day_of_calendar     - 32872     as day_key
           ,month_of_calendar   -  1080     as month_key
           ,quarter_of_calendar -   360     as quarter_key
           ,year_of_calendar    -  1989     as year_key

from        sys_calendar.calendar 

-- where       calendar_date between date '2015-09-25' and date '2015-10-05'

-- order by    calendar_date
+---------------+---------+-----------+-------------+----------+
| calendar_date | day_key | month_key | quarter_key | year_key |
+---------------+---------+-----------+-------------+----------+
| 2015-09-25    | 9,399   |       309 |         103 |       26 |
| 2015-09-26    | 9,400   |       309 |         103 |       26 |
| 2015-09-27    | 9,401   |       309 |         103 |       26 |
| 2015-09-28    | 9,402   |       309 |         103 |       26 |
| 2015-09-29    | 9,403   |       309 |         103 |       26 |
| 2015-09-30    | 9,404   |       309 |         103 |       26 |
| 2015-10-01    | 9,405   |       310 |         104 |       26 |
| 2015-10-02    | 9,406   |       310 |         104 |       26 |
| 2015-10-03    | 9,407   |       310 |         104 |       26 |
| 2015-10-04    | 9,408   |       310 |         104 |       26 |
| 2015-10-05    | 9,409   |       310 |         104 |       26 |
+---------------+---------+-----------+-------------+----------+

答案 1 :(得分:0)

RANK() OVER (ORDER BY EXTRACT(MONTH FROM CALENDAR_DATE)) AS Month_Key更改为使用DENSE_RANK,因为看起来一年中一个月的所有行都应具有相同的密钥。

SEL   calendar_date AS DATE_,
  RANK() OVER (ORDER BY calendar_date) AS Date_Key,
  DENSE_RANK() OVER (ORDER BY EXTRACT(YEAR FROM CALENDAR_DATE),EXTRACT(MONTH FROM CALENDAR_DATE)) AS Month_Key
FROM  SYS_CALENDAR.CALENDAR 
ORDER BY calendar_Date