使用Oracle从另一个表插入表值

时间:2013-06-12 04:59:12

标签: sql oracle pivot-table

我有两张桌子,

表1 包含以下字段,

u_id    id      no
12      51      1
21      51      2
31      51      3
41      51      4
51      51      5
61      51      6
72      51      7
81      51      8
91      51      9
92      51      10

表格2 包含以下字段

id      one     two     three   four    five    six     seven   eight   nine    ten

51      12      21      31      41      51      61      72      81      91      92

我需要检查一下。和表1中的id,并将相应的u_id插入表2中。

例如。如果id = 51且no为1,那么我必须将u-id值插入表2中的第一列,

并且id = 51且no = 2然后插入第二列,依此类推..请帮助。我正在使用Oracle。

4 个答案:

答案 0 :(得分:1)

如果你想创建一个新表或只需要从数据库中返回这个集合,你需要使用数据透视表来执行此操作...

select * from table 1

pivot (max (u_id) for id in ([1],[2],[3],[4],[5],[6],[7],[8],[9])[10]) as table 2

答案 1 :(得分:0)

我不认为可以使用单个查询完成。你必须为它编写一个PLSQL块。

  1. 首先列出表1中的所有唯一ID
  2. 通过for-each迭代它,并在表2的连续列中插入相应的u_id
  3. 只是一个理论上的解释。

答案 2 :(得分:0)

id必须是唯一的

select id,
sum(u_id*(if no = 1 then 1 else 0 endif)) as one,
sum(u_id*(if no = 2 then 1 else 0 endif)) as two,
sum(u_id*(if no = 3 then 1 else 0 endif)) as three,
sum(u_id*(if no = 4 then 1 else 0 endif)) as four,
sum(u_id*(if no = 5 then 1 else 0 endif)) as five,
sum(u_id*(if no = 6 then 1 else 0 endif)) as six,
sum(u_id*(if no = 7 then 1 else 0 endif)) as seven,
sum(u_id*(if no = 8 then 1 else 0 endif)) as eight,
sum(u_id*(if no = 9 then 1 else 0 endif)) as nine,
sum(u_id*(if no = 10 then 1 else 0 endif)) as ten
from table_1 group by id;

答案 3 :(得分:0)

这就是你要找的东西:

// prepopulate missing table2 entries with 0s
insert into table2 (id, one, two, three, four, five, six, seven, eight, nine, ten)
    select distinct t1.id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    from   table1 t1
    where  t1.id not in (select id from table2 t2 where t1.id = t2.id);

// update table2 entries with the values from table1
update table2 
set one = (select u_id
          from   table1 t1
          where  t1.id = table2.id
          and    t1.no = 1);

update table2 
set two = (select u_id
          from   table1 t1
          where  t1.id = table2.id
          and    t1.no = 2);

// and so on....