SQL - 仅添加前一行的值

时间:2013-12-05 22:19:27

标签: sql sql-server-2012

我有一个名为myvals的表,其中包含以下字段:

ID   number
--   -------
1     7
2     3
3     4
4     0
5     9

从第2行开始,我想添加前一行号码。所以,我的最终结果看起来像这样

ID   number
--   ------
1      7
2     10
3      7
4      4
5      9

3 个答案:

答案 0 :(得分:5)

您可以使用LAG分析函数

SELECT Id, number + LAG(number,1,0) OVER (ORDER BY Id) FROM table

答案 1 :(得分:0)

首先是第一件事。您不能将ID添加到null,必须具有值。

答案 2 :(得分:-1)

create table #temp
(
    month_type datetime,
    value int


)
insert into #temp
Select '2015/01/01',1
union
Select '2015/02/01',2
union
Select '2015/03/01',3
union
Select '2015/04/01',4



SELECT t.value,t1.value,(t.value+t1.value)/2 FROM #temp t1
left join #temp t on t.month_type=Dateadd(MONTH,-1,t1.month_type)