0

如果值不为空,如何从 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)

非常感谢您的帮助

4

3 回答 3

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

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

于 2013-04-16T14:32:20.170 回答
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。

于 2013-04-15T23:04:54.750 回答
0

如果您为每个类名列合并所有 3 个选择语句,那么这是如何做到的,这很容易。

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
于 2013-04-15T23:05:53.647 回答