获得累积金额

时间:2011-11-02 12:02:44

标签: mysql

假设我在mysql数据库中有一个表,如下所示,

date        inQty   outQty
2011-10-24  700.00  0.0
2011-10-01  500.00  0.0
2011-10-02  500.00  0.0
2011-10-03  550.00  0.0
2011-10-04  100.00  0.0 
2011-10-05  200.00  0.0
2011-10-05  0.00    100.0
2011-10-02  0.00    500.0
2011-10-03  0.00    150.0
2011-10-24  200.00  0.0

从上面的表中我需要查询以下结果,

date        inQty   outQty   Balance
2011-10-24  700.00  0.0      700.00
2011-10-01  500.00  0.0  500.00
2011-10-02  500.00  0.0  500.00
2011-10-03  550.00  0.0      550.00
2011-10-04  100.00  0.0  100.00
2011-10-05  200.00  0.0      200.00
2011-10-05  0.00    100.0    100.00
2011-10-02  0.00    500.0    0.0
2011-10-03  0.00    150.0    400.00
2011-10-24  200.00  0.0      500.00

如何从SQL查询中获取此信息?

1 个答案:

答案 0 :(得分:2)

我估计你正在寻找分区的累积总和。这只是猜测,因为您的帖子相当不清楚,因为数据没有明确的模式。我想我明白你驾驶的是什么......

也许您可以查看和修改帖子以使问题更清晰?

无论如何,请放手一搏。我不知道你的桌子叫什么,所以我会发表我自己的例子。

create table dateCumulative
(vDate date not null,
inQty decimal (12,2) not null default 0.0,
outQty decimal (12,2) not null default 0.0
);

insert into dateCumulative values ('2011-10-24',700.00,0.0);
insert into dateCumulative values ('2011-10-01',500.00,0.0);
insert into dateCumulative values ('2011-10-02',500.00,0.0);
insert into dateCumulative values ('2011-10-03',550.00,0.0);
insert into dateCumulative values ('2011-10-04',100.00,0.0);
insert into dateCumulative values ('2011-10-05',200.00,0.0);
insert into dateCumulative values ('2011-10-05',0.00,100.0);
insert into dateCumulative values ('2011-10-02',0.00,500.0);
insert into dateCumulative values ('2011-10-03',  0.00    ,150.0);
insert into dateCumulative values ('2011-10-24',  200.00  ,0.0);

select t.vDate,t.inQty,t.outQty,
round(t.inQtySum-t.outQtySum,2) as balance
from
( 
select 
(case when vDate = @curDate then (@inCsum := @inCsum + inQty) else @inCsum := inQty   end) as inQtySum,
(case when vDate = @curDate then (@outCsum := @outCsum + outQty) else @outCsum := outQty end) as outQtySum,
(case when vDate != @curDate then @curDate := vDate end) as dateChanged,
dc.*
from dateCumulative dc
inner join (SELECT @curDate := '1970-01-01',@inCsum:=0,@outCsum:=0) as t
order by vDate asc
) t;