创建和填充时间维度

时间:2018-04-01 19:56:44

标签: sql oracle dimensional-modeling

我的班次表中的shift_date列包含了该机构收到的班次请求的所有日期。它包含其他列,显示班次是填写还是已取消。我想用它来创建一个时间维度并链接到事实表,以找出每个月填充的班次,在一个季度取消等等。我创建了时间表如下。我在SQL开发人员中这样做,并了解维度建模,我无法理解。

我的班次表:

shift_date |shift_status|request_id|
-----------------------------------------
 09-01-2011|Filled      |8899
21-01-2011 |Cancelled   |6677

等等。 我创建了一个时间维度表,如下所示:

CREATE TABLE "DIM_TIME" 
       (    "TIME_KEY" NUMBER(10,0), 
        "FULL_DATE" DATE, 
        "DAY_NAME" VARCHAR2(9 BYTE), 
        "DAY_OF_WEEK" NUMBER(5,0), 
        "DAY_NUMBER_IN_MONTH" NUMBER(2,0), 
        "DAY_NAME_ABBREVATED" VARCHAR2(5 BYTE), 
        "WEEKDAY_FLAG" VARCHAR2(2 BYTE), 
        "WEEK_OF_THE_YEAR" NUMBER(5,0), 
        "WEEK_BEGIN_DATE" DATE, 
        "MONTH_NUMBER" NUMBER(3,0), 
        "MONTH_NAME" VARCHAR2(20 BYTE), 
        "MONTH_ABBREVATED" VARCHAR2(5 BYTE), 
        "QUARTER" NUMBER(5,0), 
        "YEAR" NUMBER(5,0), 
        "LAST_DAY_IN_MONTH_FLAG" VARCHAR2(2 BYTE)
       );

如何从shift_date列中提取日期以填充此time_dimension表?我不期待整个代码,但如果有人能指出我正确的方向,那将会有所帮助,因为我还在学习。谢谢你

1 个答案:

答案 0 :(得分:1)

这将在DIM_TIME表格中创建行:

create sequence s_time_key START WITH 1;

insert into dim_time (
  time_key,
  full_date,
  day_name,
  day_of_week,
  day_number_in_month,
  day_name_abbrevated,
  weekday_flag,
  week_of_the_year,
  week_begin_date,
  month_number,
  month_name,
  month_abbrevated,
  quarter,
  year,
  last_day_in_month_flag
)
select
  s_time_key.nextval,
  d,
  to_char(d,'Day'),   --Monday
  to_char(d,'D'),     --1-7, monday=2 in some countries, 1 in others (NLS)
  to_char(d,'DD'),    --1-31
  to_char(d,'Dy'),    --Su, Mo, ...
  decode(to_char(d,'Dy'),'Sa','N','Su','N','Y'),
  to_char(d,'IW'),    --week num ISO standard
--to_char(d,'WW'),    --week num other
  d+1-to_char(d,'D'), --first day in week, depending on NLS
  to_number(to_char(d,'MM')),
  to_char(d,'Month'),
  to_char(d,'MON'),
  to_char(d,'YYYYQ'),
  to_char(d,'YYYY'),
  decode(to_char(d+1,'DD'),'01','Y','N')
from (select distinct shift_date d from shift);
  • 在Oracle 12c中,您可以使用sequence自动增加密钥,而不是time_key来获取create table dim_time ( time_key number(10) generated by default on null as identity, ...列。

  • 上面的选择只会填充表DIM_TIME以及表SHIFT中实际存在的日期。但通常会在某个时间段内想要所有日期,例如2014年1月1日到2018年的所有日期,如下所示:用上面的sql替换最后一行:

from (
  select d from (
    select to_date('1970','YYYY')+level d from dual connect by level<=366*100
  )
  where to_char(d,'YYYY')
  between 2014 and 2018
);