2

我有一张桌子 t1:

ID    Period
---  --------
1       5
2       3
3       2

(该表实际上有 366 个不同的 ID,它们的周期可以是 23、24 或 25。)

我想在带有字段 ID 和 Hour 的表 t2 中插入多行,其中 Hour(ID) in 1 ..Period(ID):

ID    Hour
---  -----
1     1
1     2
1     3
1     4
1     5
2     1
2     2
2     3
3     1
3     2

我该怎么做?

4

2 回答 2

4

您可以通过使用model子句来实现这一点,例如:

with t1(ID, Period) as(
  select 1, 5 from dual union all
  select 2, 3 from dual union all
  select 3, 2 from dual
)
select ID
     , period as hour
  from t1
  model
  partition by (ID)
  dimension by (1 as indx)
  measures(period)
  rules(
     period[for indx from 1 to period[1] increment 1] = cv(indx)
  )

SQLFiddle 演示

结果:

        ID      HOUR
---------- ----------
         1          1 
         1          2 
         1          3 
         1          4 
         1          5 
         2          1 
         2          2 
         2          3 
         3          1 
         3          2 

 10 rows selected 

您的insert陈述可能如下所示:

insert into t2(id, hour)
   select ID
        , period
     from t1
     model
     partition by (ID)
     dimension by (1 as indx)
     measures(period)
     rules(
        period[for indx from 1 to period[1] increment 1] = cv(indx)
     )
于 2013-09-19T16:13:49.780 回答
0

测试设置:

CREATE TABLE t1 (
    ID INT PRIMARY KEY,
    Period INT NOT NULL
);

CREATE TABLE t2 (
    ID INT NOT NULL,
    Hour INT NOT NULL
    -- There would also be a PK here in real life.
);

INSERT INTO t1 VALUES (1, 5);
INSERT INTO t1 VALUES (2, 3);
INSERT INTO t1 VALUES (3, 2);

实际插入:

INSERT INTO t2
WITH CTE (ID, Hour) AS (
    SELECT ID, Period FROM t1
    UNION ALL
    SELECT ID, Hour - 1 FROM CTE WHERE Hour > 1
)
SELECT * FROM CTE;
于 2013-09-19T17:17:43.643 回答