我有一张桌子t1:
ID Period
--- --------
1 5
2 3
3 2
(该表实际上有366个不同的ID,它们的周期可以是23,24或25。)
我想在表t2中插入多行,其中包含字段ID和小时,其中小时(ID)为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
我该怎么做?
答案 0 :(得分: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)
)
结果:
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)
)
答案 1 :(得分: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;