查询以添加下一行的相同列

时间:2011-10-28 13:49:58

标签: sql-server-2008

我需要一个可以这样求和的查询(前一行与当前行)

1  1
2  3
3  5
4  7
5  9

我想要row1.MoneyPaid + row2.MoneyPaid,row2.MoneyPaid + row3.MoneyPaid,row3.MoneyPaid + row4.MoneyPaid

1 个答案:

答案 0 :(得分:1)

试试这个:

  SELECT m1.moneypaid, 
   ( SELECT TOP 1 m2.moneypaid 
     FROM @Money m2 
     WHERE m2.id <m1.id  
     ORDER BY m2.id  DESC
   ) AS Prev_Value
   ,m1.moneypaid + ( SELECT TOP 1 m2.moneypaid 
     FROM @Money m2 
     WHERE m2.id <m1.id  
     ORDER BY m2.id  DESC
   )