2016-11-10 87 views
0

如何獲取RESULT列?如何在sql組中添加下一行的值

P_Key Staff Amt EMI RESULT 
372175 9174 1584 1 1584 
372176 9174 1619 2 3203 
372177 9174 1654 3 4857 
372178 9174 1689 4 6546 
372179 9174 1726 5 8272 
699334 22057 1136 1 1136 
699335 22057 1161 2 2297 
699336 22057 1186 3 3483 
699337 22057 1212 4 4695 
699338 22057 1238 5 5933 
699339 22057 1265 6 7198 
699340 22057 1292 7 8490 
699341 22057 1320 8 9810 
699342 22057 1349 9 11159 
+0

你需要的列結果的總和?請更具體! – perodriguezl

回答

3

你似乎想要一個累計和。在SQL Server 2008中,一種方法是apply

select t.*, t2.result 
from t cross apply 
    (select sum(amt) as result 
     from t2 
     where t2.staff = t.staff and t2.emi <= t.emi 
    ) t2; 
-1

試試這個。這將在SQL Server 2012

select sum(Amt) over (partition by EMI order by EMI)as RESULT from Your_table 

工作或嘗試下面

SELECT SUM(Amt) FROM Your_table a, 
Your_table b 
WHERE b.EMI <= a.EMI 
GROUP BY a.EMI 
ORDER BY a.EMI; 
+0

'sum()over(partition by [] order by [])'適用於2012版及以上版本的'SQL Server'。第二個表不會返回所需的結果 –

+0

我已經提到它在答案,它將適用於SQL Server 2012 – mansi

+0

但他已經標記'sql server 2008' –

相關問題