Reputation: 3578
Let's assume that I have a table in a mysql database as follows,
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
and from above table I need to query following result,
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
how can I get this from a SQL query?
Upvotes: 0
Views: 268
Reputation: 9853
I reckon you're looking for a cumulative sum over a partition. This is only a guess though since your post is rather unclear since there is no clear pattern to the data. I think I understand what you're driving at though...
Perhaps you can review and edit your post to make the question clearer?
Anyway, give this a go. I don't know what your table is called so I'll post my own example.
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;
Upvotes: 2