0

假设我有一个包含列(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

4

2 回答 2

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 中实现了对leadandlag函数的支持:|)

于 2010-05-19T14:29:08.900 回答
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
于 2010-05-19T14:21:41.133 回答