2014-07-07 32 views
0

我在SQL Server中的表,我想總結與上排在T-SQL這樣的細胞:收集值

Quantity   Total 
----------------------------- 
    1    1 
    5    6 
    12    18 
    20    38 

我使用SQL Server 2008,我如何能實現這個?

問候,馬吉德。

回答

0

您正在尋找一個累計總和,它會出現。如果您正在使用SQL Server 2012或更高版本,只是做:

select quantity, sum(quantity) over (order by quantity) 
from table t; 

注意order by quantity。您需要指定累計和的排序,通常會執行另一個和。

在早期版本中,你可以使用相關子查詢做到這一點:

select quantity, 
     (select sum(t2.quantity) 
     from table t2 
     where t2.quantity <= t.quantity 
     ) as total 
from table t; 
+0

我使用SQL Server 2008 –

+0

@MajidHosseini你應該提到,從一開始。戈登不會告訴你一個不適用於你的版本的解決方案。 –

+0

@a_horse_with_no_name。 。 。事實上,在我完成答案之前,我被打斷了。我想知道爲什麼我的原始答案是低調的,因爲它明確指出了版本問題。唉。 –