我在Sql Server中有一个表,它有一列
Ef。:
AvgCall
6.25
6.25
10
12.5
24.5
6
9
3
现在通过使用这些数据我想要的结果如下所示。
AvgCall NewColumn
6.25 6.25
6.25 12.5
10 16.25
12.5 22.5
24.5 37
6 30.5
9 15
3 12
因此在输出中,NewColumn由逻辑添加,即第一行数据作为第一行,然后添加第一行+第二行,然后第二行+第三行。
如何获得我的结果?
如果您使用的是sqlserver 2012,则还可以使用如下所示的铅
select col1,col1+lead(col1) over (order by <<some orderring col>>)
from
tbl
对于SQL版本低于2012的版本使用此:
; WITH T(Nums) as
(
SELECT 6.25
UNION ALL
SELECT 6.25
UNION ALL
SELECT 10
UNION ALL
SELECT 12.5
UNION ALL
SELECT 24.5
UNION ALL
SELECT 6
UNION ALL
SELECT 9
UNION ALL
SELECT 3
), Main as
(
SELECT ROW_NUMBER () OVER (ORDER BY (SELECT NULL)) Id, *
FROM T
)
SELECT a.Nums , A.Nums + ISNULL((SELECT MAX(b.Nums) FROM Main b WHERE b.Id = a.Id-1 ),0) Col
FROM Main a
你可以使用LAG
create table #tmp(AvgCall FLOAT)
insert into #tmp
SELECT 6.25
union ALL
SELECT 6.25
union ALL
SELECT 10
union ALL
SELECT 12.5
union ALL
SELECT 24.5
union ALL
SELECT 6
union ALL
SELECT 9
union ALL
SELECT 3
;with cte
AS(
Select ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum, * from #tmp
)
select AvgCall+ISNULL(LAG(AvgCall) OVER(order by rownum),0)
from cte
drop table #tmp