日期:2014-05-17  浏览次数:20866 次

求教一个 SQL 的问题,十分感谢!
我现在有一个表,名字为 table1, 表里有两列,一列是序号ID,一列是数量 NUM1,比如

ID1 NUM1
1 20
2 30
3 50
4 10
5 20
...


要求在这个表上加一列 NUM2,表示从第 1 行到第 i 行的 NUM1 的和。对上表来说,就是

ID1 NUM1 NUM2
1 20 20
2 30 50
3 50 100
4 10 110
5 20 130
...


请问如何实现?

万分感谢!

------解决方案--------------------
SQL code
create table table1(id1 int, num1 int);
insert into table1(id1,num1) values(1,20);
insert into table1(id1,num1) values(2,30);
insert into table1(id1,num1) values(3,50);
insert into table1(id1,num1) values(4,10);
insert into table1(id1,num1) values(5,20);

update table1 t1
  set t1.num2=(select sum(num1) 
                 from table1 t2 
                where t2.id1<=t1.id1 );

------解决方案--------------------
这个可以使用窗口函数来实现。
测试数据:
SQL code

CREATE TABLE T33
(
    ID NUMBER(4),
    NUM1 NUMBER(4)
);

INSERT INTO T33 VALUES(1, 20);
INSERT INTO T33 VALUES(2, 30);
INSERT INTO T33 VALUES(3, 50);
INSERT INTO T33 VALUES(4, 10);
INSERT INTO T33 VALUES(5, 20);

------解决方案--------------------
SQL code

SELECT t.id1,
       t.num1,
       SUM(t.num1) OVER(ORDER BY t.id1) num2
  FROM table1 t