上一行值添加到当前行,依此类推SQL Server

时间:2016-11-15 15:42:56

标签: sql-server sql-server-2012

我使用的是2012版。

我有这个数据表。

        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 个答案:

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