2011-11-02 110 views
0

让我们假设我有一个表在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

您的示例没有任何意义 –

+1

第一个数据集中的0.0900.00是什么?为什么最后一行的平衡是500?难道不是900?检查并更正您的示例。 – Devart

回答

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;