to  liuyi8903(甜脆夹心) :能否指点一二,在下感觉不尽!

解决方案 »

  1.   

    行列转列后,再对结果集做分组SUM就行了
      

  2.   

    to  ORARichard(没钱的日子......) 
    如何分组?group by 后只能接一个字段呀!!!
      

  3.   

    你看这是不是你要的?SQL> select * from test;COL1       COL2       COL3       TYPE  VALUE1 VALUE2
    ---------- ---------- ---------- ----- ------ ------
    a          b          c          2          4      6
    x          y          z          2          7      5
    x          y          z          1          8      9
    a          b          c          1          3      2SQL> 
    SQL> Select Col1,
      2         Col2,
      3         Col3,
      4         Sum(Decode(Type, 1, Value1)) Type1,
      5         Sum(Decode(Type, 2, Value1)) Type2,
      6         Sum(Value2)
      7    From Test
      8   Group By Col1, Col2, Col3
      9  ;COL1       COL2       COL3            TYPE1      TYPE2 SUM(VALUE2)
    ---------- ---------- ---------- ---------- ---------- -----------
    a          b          c                   3          4           8
    x          y          z                   8          7          14SQL>
      

  4.   

    当然这里如果是type的值比较固定的话可以这样来使用.
    假如type的值很多,且无法估算的话,那就要用动态sql了.编写存储过程可以解决.
      

  5.   

    SQL>  create or replace view tbview
      2   as
      3   select col1,col2,col3,
      4          sum(decode(type,1, value1)) type1,
      5          sum(decode(type,2, value1)) type2
      6   from tb
      7   group by col1,col2,col3;查看已建立。SQL> select * from tb;CO CO CO TY VA VA
    -- -- -- -- -- --
    a  b  c  1  3  2
    x  y  z  2  7  5
    a  b  c  2  4  6
    x  y  z  1  8  9SQL> select * from tbview;CO CO CO     TYPE1     TYPE2
    -- -- -- --------- ---------
    a  b  c          3         4
    x  y  z          8         7SQL>  select a.*,b.sumvalue2 from tbview a,
      2   (
      3       select col1,col2,col3,sum(value2) sumvalue2 from tb
      4           group by col1,col2,col3
      5   ) b
      6   where a.col1=b.col1 and a.col2=b.col2 and a.col3=b.col3;CO CO CO     TYPE1     TYPE2 SUMVALUE2
    -- -- -- --------- --------- ---------
    a  b  c          3         4         8
    x  y  z          8         7        14SQL>
      

  6.   

    哈,liuyi8903(甜脆夹心)
    还是老兄高啊。我怎么就给绕到那个视图里去了啊
      

  7.   

    :)  ORARichard(没钱的日子......) 老兄太谦虚了!
      

  8.   

    响应1楼,给个分析函数的做法:
    select 
      dmp.col1,
      dmp.col2,
      dmp.col3,
      sum(nvl(type2,0)) type1,
      sum(nvl(type1,0)) type2,
      sum(value2)
    from
    (select col1,
           col2,
           col3,
           decode(type,
                  1,
                  lead(value1, 1) over(order by col1, col2, col3,type,0)) type1,
           decode(type,
                  2,
                  lag(value1, 1) over(order by col1, col2, col3,type,0)) type2,
           value2  
      from my_test) dmp
    group by
      dmp.col1,
      dmp.col2,
      dmp.col3