Reputation: 27
I have 2 tables ,
table 1 has the following fields ,
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
table 2 has the following fields,
id one two three four five six seven eight nine ten
51 12 21 31 41 51 61 72 81 91 92
I need to check the no. and the id from table 1 and insert the corresponding u_id into the table 2.
for eg. if the id = 51 and the no is 1, then I have to insert the u-id value into the column one in table 2,
and id = 51 and no = 2 then insert into column two and so on .. Please help . I am using Oracle.
Upvotes: 0
Views: 4175
Reputation: 321
If you want to create a new table or just need to return this set from database, you will require pivot table to do this...
select * from table 1
pivot (max (u_id) for id in ([1],[2],[3],[4],[5],[6],[7],[8],[9])[10]) as table 2
Upvotes: 1
Reputation: 511
Is this what you are looking for:
// 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....
Upvotes: 0
Reputation: 16
id must be unique
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;
Upvotes: 0
Reputation: 10894
I don't think it can be done with a single query. You have to write a PLSQL block for it.
Just a theoretical explanation.
Upvotes: 0