2017-04-07 28 views
1

Folk,使用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人口stucked,我不與remaing代碼實現...

+0

到底是什麼問題?您是否擔心排名跳過數字或其他內容? – Andrew

回答

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 
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 | 
+---------------+---------+-----------+-------------+----------+ 
+0

基本上我試圖建立一個SQL腳本的時間維度,這對Teradata&SQL Server也是有用的(儘管在腳本中可能需要小的語法修改)....在提供的答案中,我不確定你爲什麼從列中減去數字?例如: - day_of_calendar - 32872 as day_key – Aditya

+0

Teradata日曆表從1900-01-01開始。減法是爲了使它符合你的要求結果 –