如何将一个列数据从一个表中获取到另一个表中作为PL / SQL中的不同列

时间:2013-07-18 06:49:10

标签: sql oracle plsql

我在一个名为

的表中有一个数据
unsorted

Scott
100
10
Miller
200
20
Mike
300
30
Allen
400
4

现在,我希望上面的数据在另一个以3列

排序的表中
name   sal   deptno

Scott  100   10
Miller 200   20
Mike   300   30
Allen  400   40

我正在处理PL / SQL查询但要检索我想在每列中给出

我尝试了不同的方法,但显示出一些错误。

DECLARE 
  CURSOR raw_cur IS 
     SELECT raw_data 
       from table_a; 
  raw_rec raw_cur%ROWTYPE; 
BEGIN 
  OPEN raw_cur; 
  LOOP 
    FETCH raw_cur INTO raw_rec; 
    EXIT WHEN raw_cur%NOTFOUND; 
    INSERT INTO Temp_process(Name ,Sal , Deptno) 
      VALUES(raw_rec.Name, raw_rec.Sal, raw_rec.Deptno); 
  END LOOP; 
  COMMIT; 
  CLOSE raw_cur; 
END;

1 个答案:

答案 0 :(得分:2)

如果您保证源表中的数据将按此特定顺序排列,您可以编写类似的查询以获得所需的结果:

-- sample of data from your question
SQL> with t1(col) as(
  2    select 'Scott'  from dual union all
  3    select '100'    from dual union all
  4    select '10'     from dual union all
  5    select 'Miller' from dual union all
  6    select '200'    from dual union all
  7    select '20'     from dual union all
  8    select 'Mike'   from dual union all
  9    select '300'    from dual union all
 10    select '30'     from dual union all
 11    select 'Allen'  from dual union all
 12    select '400'    from dual union all
 13    select '40'     from dual
 14  ) -- the query
 15  select max(decode(mod(rownum - 1, 3), 0, col)) as name
 16       , max(decode(mod(rownum - 1, 3), 1, col)) as sal
 17       , max(decode(mod(rownum - 1, 3), 2, col)) as depno
 18    from t1
 19    group by trunc((rownum -1)/ 3)
 20  /

NAME   SAL    DEPNO
------ ------ ------
Miller 200    20
Mike   300    30
Allen  400    40
Scott  100    10

<强>附录

你不需要一个游标(除非它是某种特殊要求,需要使用游标)。要使用数据填充其他表格,您只需使用INSERT INTO ... SELECT

insert into temp_process(name, sal, depno)
   select max(decode(mod(rownum - 1, 3), 0, col)) 
        , max(decode(mod(rownum - 1, 3), 1, col)) 
        , max(decode(mod(rownum - 1, 3), 2, col))
     from table_a
     group by trunc((rownum -1)/ 3)