有表testsum
  a       b
  1       2
  2       3
  3       4
  4       5
  5       6
  6       7
  7       8
  8       9
  9       10
要求用SQL语句查询出下表结果
  a      sum
  1       2
  2       5
  3       9
  4       14
  5       20
  6       27
  7       35
  8       44
  9       54
有大神能够帮忙么。。

解决方案 »

  1.   

    select t1.a, sum(t2.b) b
      from test t2, test t1
     where t2.a <= t1.a
     group by t1.a
     order by t1.a
    结果:
    A B
    1 2
    2 5
    3 9
    4 14
    5 20
    6 27
    7 35
    8 44
    9 54
      

  2.   

    开窗函数sum() over()
    with t1 as
    (
         select 1 a,2 b from dual union all
         select 2 a,3 b from dual union all
         select 3 a,4 b from dual union all
         select 4 a,5 b from dual union all
         select 5 a,6 b from dual
    )select a,sum(b) over(order by a) b
    from t1     a     b
    ---------------------
    1 1 2
    2 2 5
    3 3 9
    4 4 14
    5 5 20
      

  3.   

    5楼说的对,是分析函数的典型用法。自己属于菜鸟,基于2楼提出的写个过程,具体如下,请勿喷,哈哈CREATE TABLE TEST (ID NUMBER,VALUE NUMBER);
    CREATE TABLE TEST_RESULT AS SELECT * FROM TEST WHERE 1=0;CREATE OR REPLACE PROCEDURE TEST_01 AS
      V1_MAX NUMBER;
      V2     NUMBER(2) := 1;
      V3     NUMBER := 0;
      V4     NUMBER := 0;
    BEGIN
      SELECT MAX(ID) INTO V1_MAX FROM TEST;
      --SELECT VALUE INTO V3 FROM TEST WHERE ID = 1;
      while (V2 <= V1_MAX) loop
        SELECT VALUE INTO V4 FROM TEST WHERE ID = V2;
        v3 := v4 + v3;
        INSERT INTO TEST_RESULT VALUES (V2, V3);
        v2 := v2 + 1;
        commit;
      END loop;
    END;