0

我有 2 张桌子,

表 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 然后插入到第二列等等..请帮助。我正在使用甲骨文。

4

4 回答 4

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
于 2013-06-12T05:45:34.383 回答
0

我不认为它可以通过一个查询来完成。您必须为它编写一个 PLSQL 块。

  1. 首先列出表 1 中的所有唯一 ID
  2. 通过 for-each 对其进行迭代,并在表 2 的连续列中插入相应的 u_id

只是理论上的解释。

于 2013-06-12T05:10:37.330 回答
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;
于 2013-06-12T05:34:05.600 回答
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....
于 2013-06-12T05:44:22.757 回答