两个相邻列求和

来源:互联网 发布:乌恰县网站域名官网 编辑:程序博客网 时间:2024/04/29 17:48

1     3
2     7
3     11
4
5
6

左边这个是一个数据表中的值,我要每两行求和,最后的结果是右边这个表,SQL怎么写?

 

 

答案:

if object_id('[test]') is not null drop table [test]
go
create table [test]([t1] int)
insert [test]
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 

select t=t1 + isnull((select top 1 t1 from test where t1>t.t1),0)  
from [test] t
where  t.t1%2=1

原创粉丝点击