2013-06-12 23 views
0

我有2個表的另一個表,插入到一個表中的值從使用Oracle

表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 

我需要檢查no。和表1中的id並將相應的u_id插入到表2中。

例如,如果id = 51且no爲1,那麼我必須將u-id值插入到表2中的第一列中,

和id = 51並且no = 2,然後插入到第二列中,依此類推。 。 請幫忙 。我正在使用Oracle。

+1

你能給我們多一點背景嗎?你想要做什麼語言,什麼樣的桌子等。乾杯。 – JanR

回答

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; 
+1

如果您將非標準的'if'更改爲標準'case'表達式,這應該適用於Oracle(該dppp正在使用) - 但不需要與u_id相乘。 –

+0

謝謝。這對我有用 – guitarist

0

我不認爲它可以完成一個單一的查詢。你必須爲它編寫一個PLSQL塊。

  1. 首先列出了從表中通過所有的唯一ID 1
  2. 迭代它的for-each和插入表2

只是理論上的解釋相應的U_ID在連續的列。

+0

對不起,我正在使用oracle來完成上述操作。 – guitarist

+0

那麼,你可以在Oracle中編寫PLSQL! ! –

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.... 
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 
相關問題