2013-11-15 258 views
0

我在我的表中的數據如下,遞歸函數

+----+-----+ 
| ID | Qty | 
+----+-----+ 
| 1 | 100 | 
| 2 | 200 | 
| 3 | 150 | 
| 4 | 50 | 
+----+-----+

我需要的結果如下,

+----+-----+-------+ 
| ID | Qty | C.Qty | 
+----+-----+-------+ 
| 1 | 100 | 100 | 
| 2 | 200 | 300 | 
| 3 | 150 | 450 | 
| 4 | 50 | 500 | 
+----+-----+-------+

第三列的結果將是以前行的總和, 請任何一個幫助....

+0

我不明白...哪裏了'500'從何而來? –

+0

@PaulDraper 450 + 50 = 500 .. –

+0

它已經被回答[here](http://stackoverflow.com/questions/2120544/how-to-get-cumulative-sum) – remigio

回答

2

我只想用一個子查詢:

SELECT ID, Qty, 
    (SELECT SUM(Qty) FROM [My Table] b WHERE b.ID <= [My Table].ID) AS [Total Qty] 
FROM [My Table] 
+0

感謝它的工作 – user2249248

2

請嘗試:

SELECT S1.ID, S1.Qty ,sum(S2.Qty) CUM_SUM 
FROM YourTable S1 join YourTable S2 
on S1.ID>=S2.ID 
group by S1.ID, S1.Qty 
ORDER BY S1.ID 
1
SELECT ID, Qty, 
SUM(Qty) OVER(ORDER BY ID 
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) 
     AS C.QTY 
FROM Table 
+0

看起來很有趣。這是什麼數據庫服務器? – David

+0

這是ANSI-SQL –

+0

@David Sql Server 2012(以前不支持)。不知道甲骨文何時開始支持它。至少工作11g。如果它能夠運行postgresql,不會感到驚訝。絕對不會在MySQL中工作 –

0

試試這個:

select a.id,a.qty,sum(b.qty) as total_qty 
from table a cross join table b 
where b.id <= a.id 
group by a.id,a.qty 
order by a.id 

demo