2016-11-15 67 views
0

我使用的2012年版前行值加到当前行等上的SQL Server

我有这个表中的数据。

 create table #temp_metrics 
     (
      id int identity(1,1) 
      ,prev_total int not null default(0) 
      ,added int not null default(0) 
      ,total int not null default(0) 
     ) 

     insert into #temp_metrics 
     (
      added 
     ) 
     values 
     (
      10 
     ),(20),(5),(15),(9) 

     select * from #temp_metrics 

我期待输出如下

enter image description here

前行总计应该是当前行prev_total

总应该是以前的行总计+添加

我使用以下查询

 ;WITH CTE AS (
        SELECT 
         id 
         ,Total 
        from 
         #temp_metrics 
        ) 
     SELECT 
       prev.total as prev_total 
       ,t.added 
       ,prev.total +t.added as total 
     FROM 
      #temp_metrics t 
      LEFT JOIN CTE prev ON prev.id = t.id - 1 

但看起来像我失去了一些东西。

如何获取图像格式的输出?

在此先感谢。

+2

的[http://stackoverflow.com/questions/可能的复制860966/calculate-a-running-total-in-sql-server](http://stackoverflow.com/questions/860966/calculate-a-running-total-in-sql-server) – wdosanjos

回答

1

你可以尝试

Select ID 
     ,Prev_Total = sum(Added) over (Order By ID) -Added 
     ,Added 
     ,totoal = sum(Added) over (Order By ID) 
From #temp_metrics 
Order By ID 

返回

ID Prev_Total Added totoal 
1 0   10  10 
2 10   20  30 
3 30   5  35 
4 35   15  50 
5 50   9  59 
+1

这个答案对未来的读者有用,如果它有解释为什么它的工作。我不得不做很多研究来找出为什么它不会为每一行都产生相同的“全部”。 –

0

为此,您可以使用金额和滞后

;with cte as (
select *, RunningTotal = sum(added) over(order by id) from #temp_metrics 
) 
select *, lag(RunningTotal,1, 0) over(order by id) as Prev_total from cte