表:tb_test
列:id、year、month、sort、value
其中value保存的是本年从1月到该月的累积数量
sort一共有12种,也就是说每月有12条记录现在要求写一个存储过程,以年份和月份为参数,返回12条记录,其中value值为当月数量(也就是该月的value-上月value)数据库方面比较菜,这个问题一直解决不了,各位大哥帮帮忙啊!谢谢了!

解决方案 »

  1.   

    若可以使用Oracle地分析函数,可以这样:
    select id,year,month,sort,value,value-nvl(lag(value,1) over (order by year,month),0)
    from tb_test
      

  2.   

    create or replace procedure v_csdn is
      v_id varchar2(20); 
      num number :=0; 
      v_year number;
      v_month number; 
      v_value number; 
      v_value1 number; 
      v_sort number :=1; 
      v_b number := 1;
      v_y number; 
      cursor cur is select t.id,t.year,t.month,t.value,t.sort from v_tb_test t order by t.sort,t.year,t.month; 
    begin 
      open cur;
      loop 
      fetch cur into v_id,v_year,v_month,v_value,v_sort; 
      exit when cur%notfound; 
      if (v_sort = v_b) and (v_year = v_y) then 
      insert into v_tb_test1 values(v_id,v_year,v_month,v_sort,v_value-num);
      commit; 
      num :=v_value;
      else
      insert into v_tb_test1 values(v_id,v_year,v_month,v_sort,v_value);
      commit;
      v_b := v_sort;
      v_y := v_year;
      num :=v_value;
      end if;   
      end loop; 
      close cur; 
    exception when others then 
     dbms_output.put_line(sqlerrm); 
     rollback; 
    end; 
      

  3.   

    第1次在csdn上回答问题,
    不知道可不可以得分,
    呵呵
    感觉楼主说的功能还是基本能实现的