2011-11-02 175 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;