现在有个表:如下
units subject cyear m1    m2     m3    m4    m5  m6  m7  m8  m9   m10  m11  m12
单位1  科目1   2005  10.00 200.00 22.00 52.00 22  22  87  22  32   22   222  222
单位1  科目2   2005  10.00 200.00 22.00 52.00 22  22  87  22  32   22   222  222
单位1  科目3   2005  10.00 200.00 22.00 52.00 22  22  87  22  32   22   222  222
单位1  科目4   2005  10.00 200.00 22.00 52.00 22  22  87  22  32   22   222  222
单位2  科目1   2005  10.00 200.00 22.00 52.00 22  22  87  22  32   22   222  222
....
现在需要通过查询语句把这个表查询成
units cyear  科目1                 科目2      科目3     科目4
单位1  2005  科目1 12个月的累计数    ... .. ..
单位2  2005  科目1 12个月的累计数    0 0 0
把科目变成字段,字段的值是每个科目的累加数,如果没有记录的就变成0
我现在是通过写一个函数来实现的,请问大家有没有别的什么更好的办法啊,可不可以直接用sql语句实现了
如果我用函数写,应该注意什么了,这个表的数据大概有700万条。要怎么写效率才高了,

解决方案 »

  1.   

    http://community.csdn.net/Expert/topic/4959/4959619.xml?temp=.4998743应该使用到函数,建立函数索引可以提高效率
      

  2.   

    create table ttt
    (ids number,
     ty number,
     salary number,
     s number
    )insert into ttt values(1, 1, 10, 10);
    insert into ttt values(1, 2, 100, 100);
    insert into ttt values(1, 3, 1000, 1000);
    insert into ttt values(1, 4, 10000, 10000);
    insert into ttt values(2, 1, 20, 20);
    insert into ttt values(2, 2, 200, 200);
    insert into ttt values(2, 3, 2000, 2000);
    insert into ttt values(2, 4, 20000, 20000);
    IDS TY SALARY S
    --  -- ------ --
    1 1 10 10 
    1 2 100 100 
    1 3 1000 1000 
    1 4 10000 10000 
    2 1 20 20 
    2 2 200 200 
    2 3 2000 2000 
    2 4 20000 20000 select  ids, sum(decode(ty,1, salary+s,null)) "a", 
                 sum(decode(ty,2, salary+s,null)) "b", 
                 sum(decode(ty,3, salary+s,null)) "c", 
     sum(decode(ty,4, salary+s,null)) "d" 
    from ttt
    group by idsIDS A  B  C   D
    --  -- -- --  ---
    1 20 200 2000 20000 
    2 40 400 4000 40000 楼主的就这样:
    select  units, cyear,  
            sum(decode(subject,'科目1' ,m1+m2+m3+m4+m5+m6+m7+m8+m9+m10+m11+m12, null)) "科目1", 
            sum(decode(subject,'科目2' ,m1+m2+m3+m4+m5+m6+m7+m8+m9+m10+m11+m12, null)) "科目2", 
            sum(decode(subject,'科目3' ,m1+m2+m3+m4+m5+m6+m7+m8+m9+m10+m11+m12, null)) "科目3",
            sum(decode(subject,'科目4' ,m1+m2+m3+m4+m5+m6+m7+m8+m9+m10+m11+m12, null)) "科目4",
    from tmp
    group by units
      

  3.   

    SQL能实现,上面给出的就可以。我测试过的了。
      

  4.   

    谢谢各位,那请问,是用函数效率高,还是用sql语句效率高了