2010-05-19 61 views
0

假设我有一个列(大卫·,RunningTotal)的表:SQL选择逐行增加

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

如何选择的大卫·和RunningTotal已经从量增加前一天?即如何选择:

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

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

编辑:使用MS SQL Server 2005的

+0

您能添加一个列,告诉你前一天吗? – Avitus 2010-05-19 14:14:56

+1

哪个数据库服务器和版本? – araqnid 2010-05-19 14:15:06

+1

你使用什么数据库? – 2010-05-19 14:15:06

回答

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 

(我真希望他们能为lead实施支持和lag函数在SQL Server中:|)

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