没有人遇到过这种情况吗?忘了说还有一个条件:
      A         B            FLAG
 ---------------------------------------------
     1          AAA1         1
     1          BBB1         2
     2          AAA2         1
     2          BBB2         2
如果用SELECT .. FROM a X,a Y WHERE ...  感觉选择的速度相当慢,有没有效率高一点的方法?

解决方案 »

  1.   

    SQL> select * from aa;         A B          FLAG
    ---------- ---- ----------
             1 AAA1          1
             1 BBB1          2
             2 AAA2          1
             2 BBB2          2SQL> select A,max(b) B,max(C) C from
      2  (select aa.a,decode(aa.flag,1,b,'') B,decode(aa.flag,2,b,'') C from aa)
      3  group by a
      4  /         A B    C
    ---------- ---- ----
             1 AAA1 BBB1
             2 AAA2 BBB2
      

  2.   

    TO: ATGC,非常谢谢你。
      但是感觉 select x.a,x.b ,y.b as c
    from aa x,aa y
    where x.flag= '1' and
          y.flag= '2' and
          x.a= y.a
    要快很多阿。
      

  3.   

    这样可能比刚才会快点
    SQL> select a,max(decode(flag,1,b,'')) B,max(decode(flag,2,b,'')) C from aa
      2  group by a
      3  /         A B    C
    ---------- ---- ----
             1 AAA1 BBB1
             2 AAA2 BBB2
      

  4.   

    还有这个
    select x.a,x.b,y.b c
    from 
    (select aa.a,aa.b from aa where flag='1') x,
    (select aa.a,aa.b from aa where flag='2') y
    where x.a = y.a;
      

  5.   

    to ATGC我觉得你这句
    select a,max(decode(flag,1,b,'')) B,max(decode(flag,2,b,'')) C from aa group by a
    和楼主自己写的都满好。你最后一种方法有缺陷。如:
    A             B           FALG
    -             ----        ----
    1             AAA1        1
    1             BBB1        2
    2             AAA2        1
    3             BBB3        2
      

  6.   

    select a,max(decode(c,1,b,0)) b1,max(decode(c,2,b,0)) b2,max(decode(c,3,b,0)) b3
    from (
        select a,b,dense_rank() over (partition by a order by b) c
        from   vTable
    )
    group by a如果无法确定每个组的行数,那么只好用动态sql实现:
    declare
        cnt  number;
        vSQL varchar2(5000);
        vCol varchar2(100) := ', max(decode(c,:x,b,0)) b:x'
    begin
        select max(cnt) into cnt
        from   (
            select count(*) cnt
            from   vTable
        );
        for i in 1..cnt loop
            vSQL := vSQL || replace(vCol,':x',i);
        end loop;
        vSQl := 'select a' || vSQL || chr(10) || 'from (
        select a,b,dense_rank() over (partition by a order by b) c
        from   vTable)';
        
        --生成的SQL语句就是所要的SQL语句
       ...
    end;
      

  7.   

    select a,max(decode(flag,1,b,'')) B,max(decode(flag,2,b,'')) C from aa group by a
    这个选择感觉满清晰的,速度也比以前的快了很多。谢谢了。