SQL选择逐行增加运行总列数

时间:2010-05-19 14:12:58

标签: sql refactoring running-total

假设我有一个包含列的表(DayId,RunningTotal):

DayId    RunningTotal
---------------------
1        25
3        50
6        100
9        200
10       250

如何选择DayId以及RunningTotal从前一天增加的金额?即我如何选择:

DayId    DayTotal
---------------------
1        25
3        25
6        50
9        100
10       50

我所知道的唯一当前方法是使用while循环我试图分解。此外,DayId没有常规规则,只是它是一些递增的整数值,但它增加了不规则的数量,如示例表中所示。

编辑:使用MS SQL Server 2005

2 个答案:

答案 0 :(得分:1)

with cte as (
  select dayid, runningtotal, row_number() over (order by dayid asc) as row_index
  from #the_table
)
select cur.dayid, cur.runningtotal - coalesce(prev.runningtotal, 0) as daytotal
from cte cur
     left join cte prev on prev.row_index = cur.row_index - 1

(我真的希望他们在SQL Server中实现对leadlag函数的支持:|)

答案 1 :(得分:0)

可能比这更简洁,但请尝试:

select t3.DayId, 
    case when t4.DayId is null then t3.RunningTotal else t3.RunningTotal - t4.RunningTotal end as DayTotal
from (
    select t1.DayId, max(t2.DayId) as PreviousDayId as 
    from MyTable t1
    left outer join MyTable t2 on t2.DayId < t1.DayId
    group by t1.DayId    
) a
inner join MyTable t3 on a.DayId = t3.DayId
left outer join MyTable t4 on a.PreviousDayId = t4.DayId