逐行累加,最好是在应用程序端用编程的方法解决。数据库端用SQL语句实现累加需求,数据表须要有一个自增ID列,但是系统开销会比较大。下面是示范语句供参考:
-- 利用自增id列实现累加SQL语句
select t.*,
(select sum(num) from test where id<=t.id)
as AcmNum from test t
源表数据如图
累加运行效果如图
创建表:
create table test(date datetime,
userid varchar(2),
amount int)
insert into test values ('2018-10-02 00:00:00','u1',20)
insert into test values ('2018-10-02 21:09:28','u2',20)
insert into test values ('2018-10-02 21:09:29','u3',30)
insert into test values ('2018-10-03 21:36:44','u1',20)
insert into test values ('2018-10-03 21:36:46','u2',72)
insert into test values ('2018-10-03 21:36:52','u3',30)
insert into test values ('2018-10-30 21:36:54','u1',10)
insert into test values ('2018-10-30 21:36:57','u2',10)
执行:
select a.date,a.userid,a.amount,sum(b.amount) from test a,test b where a.userid=b.userid and a.date>=b.date group by a.date,a.userid,a.amount结果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)