有如下的表Test(id,pid)
其中pid是id的上一级标识,现在要求进行行转列。
假设有如下数据:
1 2
2 3
3 4
4 null
期待结果如下
1 2,3,4
2 3,4
3 4
4 null请问这个sql怎么写? 
在线等待!很快给分!

解决方案 »

  1.   

    转别人的在oracle里面写个方法   
      function   test(in_id   in   number)   return   varchar2   IS   
      l_search_cur   IS   REF   CURSOR;   
      l_pid   varchar2   
      l_result   varchar2   
      BEGIN   
      OPEN   l_search_cur   FOR   
      select   pid   from   A   where   id   =   in_id   
      LOOP   
      FETCH   l_search_cur   INTO   
      l_pid   
      EXIT   WHEN   l_search_cur%NOTFOUND   
      l_result   :=   l_result   ||   l_pid   ||   ',';   
      END   LOOP;   
      l_result   :=   substr(l_result,1,length(l_result)-1);     
      return   l_result;   
      END   test;   
        
      然后查询的时候   
      select   id,test(id)   pid   from   A   
      写在Package里面可用,这是我常用的方法。或许还有更好的
      

  2.   

    col path format a50select id, substr(replace(path,','||id,''),2) path from
    (
    select id,pid,sys_connect_by_path(id,',') as path
     from test
    start with pid is null
    connect by prior id=pid
    order by id);结果是
    ID PATH
    -- -------
     1 4,3,2
     2 4,3
     3 4
     4要把结果反转下才好
      

  3.   

    这下可以了
    col path format a50 select id, reverse(substr(replace(path,','||id,''),2)) path from 

    select id,pid,sys_connect_by_path(id,',') as path 
    from test 
    start with pid is null 
    connect by prior id=pid 
    order by id); 
      

  4.   


    10G版本就是爽!转换函数一换,OK!