如何在sql中添加组中下一行的值

时间:2016-11-10 12:08:18

标签: sql sql-server sql-server-2008

如何获得RESULT列?

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

2 个答案:

答案 0 :(得分: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 :(得分:-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;