这个用一句sql恐怕写不出来啊吧,主要难点在于 一共有哪些列 是要靠拼串拼出来的。可以用个存储过程把sql语句拼出来。

解决方案 »

  1.   

    --测试
    declare col1 test.f1%type;        --定义类型
    sqlstr varchar2(4000);
    cursor c_try is select distinct f1 from test;
    begin
        sqlstr:='';
        open c_try;
        loop
        fetch c_try into col1;
        exit when c_try%notfound;
        sqlstr:=sqlstr||', sum(decode(f1,'''||col1||''',1,null)) as '||col1;
        exit when c_try%notfound;
        end loop;
        close c_try;
        sqlstr:='create table tt as select '||substr(sqlstr,2)||' from test';
       --tt为刚创建的一个保存结果的表
       execute immediate sqlstr;
    end;--执行
    select * from tt;
      

  2.   

    --测试
    declare col1 test.f1%type;        --定义类型
    sqlstr varchar2(4000);
    cursor c_try is select distinct f1 from test;
    begin
        sqlstr:='';
        open c_try;
        loop
        fetch c_try into col1;
        exit when c_try%notfound;
        sqlstr:=sqlstr||', decode(f1,'''||col1||''',1,null) as '||col1;
        exit when c_try%notfound;
        end loop;
        close c_try;
        sqlstr:='create table tt as select '||substr(sqlstr,2)||' from test';
       --tt为刚创建的一个保存结果的表
       execute immediate sqlstr;
    end;--执行
    select * from tt;
      

  3.   

    谢谢楼上
    第2个测试结果正确。但是有个小的瑕疵:f1字段在新创建的tt表中未包含,请高手再帮我添上吧。
      

  4.   

    --测试
    declare col1 test.f1%type;        --定义类型
    sqlstr varchar2(4000);
    cursor c_try is select distinct f1 from test;
    begin
        sqlstr:='';
        open c_try;
        loop
        fetch c_try into col1;
        exit when c_try%notfound;
        sqlstr:=sqlstr||', decode(f1,'''||col1||''',1,null) as '||col1;
        exit when c_try%notfound;
        end loop;
        close c_try;
        sqlstr:='create table tt as select f1'||sqlstr||' from test';
       --tt为刚创建的一个保存结果的表
       execute immediate sqlstr;
    end;--执行
    select * from tt;
      

  5.   

    ok了。
    谢谢 子陌红尘 的帮助。
    实际工作中,需要查询多次,有可能test表的数据变化了就进行查询。所以我在上述代码中加入了删除上次tt表的代码。最后结果如下:
    declare col2 test.f1%type;        
    sqlstr varchar2(4000);
    sqlstr2 varchar2(200);
    cursor c_try is select distinct f1 from test;
    begin
        sqlstr:='f1,f2';
        sqlstr2:='drop table tt';
        open c_try;
        loop
        fetch c_try into col2;
        exit when c_try%notfound;
        sqlstr:=sqlstr||', decode(f1,'''||col2||''',1,null) as '||col2;
        exit when c_try%notfound;
        end loop;
        close c_try;
        --delete table tt
        begin
        execute immediate sqlstr2;
        exception
        when others then
          if sqlcode!=-942 then  -- 492 error:table already not exist
            raise;
          end if;
        end;
        --create table tt
        sqlstr:='create table tt as select '||substr(sqlstr,1)||' from test';
        execute immediate sqlstr;
    end;
    /