0

我在一个名为的表中有一个数据

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;
4

1 回答 1

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)  
于 2013-07-18T07:47:40.420 回答