从1个表中选择多个列插入另一个表的多个行

时间:2013-04-15 22:40:38

标签: sql oracle

如果值不为null,如何从table1中选择多个列并插入table2的多行

create table table2
(
label_id NUMBER(4),
level_name VARCHAR2(20)
);

create table table1 
(
level_name VARCHAR2(20), 
class_name1 VARCHAR2(20),
class_name2 VARCHAR2(20),
class_name3 VARCHARS2(20)
)


create table table2
(
   level_id NUMBER(4),
   class_name VARCHAR2(20)
)

data in table0
1, k1
2, k2

data in table1
k1, roomA5, roomA6, roomA7
k2, roomB1, roomB2

the result table2 
1, roomA5
1, roomA6
1, roomA7
2, roomB1
2, roomB2

我可能需要在table2中添加另一列才能使其正确。也许table2应该是(level_id,room_id,class_name)

非常感谢你的帮助

3 个答案:

答案 0 :(得分:0)

尝试:

insert into Table2 t2
( 
  Level_Id,
  Class_Name  
)select 
   t0.Level_Id, 
   t1.Class_Name1
 from  Table0 t0
 inner join Table1 t1 on t1.level_name = t0.level_name 

对每个类执行此操作,只需将Class_Name1替换为Class_Name2。

答案 1 :(得分:0)

如果你为每个classname列合并所有3个select语句,那么如何操作就很容易。

insert into table2 
  select a.level_id, b.classname1
  from table0 a
  join table1 b on a.level_name = b.level_name
  where b.classname1 is not null
union all
  select a.level_id, b.classname2
  from table0 a
  join table1 b on a.level_name = b.level_name
  where b.classname2 is not null
union all
  select a.level_id, b.classname3
  from table0 a
  join table1 b on a.level_name = b.level_name
  where b.classname3 is not null

答案 2 :(得分:0)

您是否看过unpivot命令?

http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html

当然,这假设你使用的是oracle 11g,这是一个假设。

insert into table2  
select *
  from table1
unpivot
(
  level_name 
  for class_name in ("class_name1","class_name2","class_name3")
)
order by "Puchase Frequency", state_code

我没有要测试的数据库,但这可能有所帮助。这似乎是一种干净的方式。