SQL Server求连续n行的和

来源:互联网 发布:影楼美工师招聘 编辑:程序博客网 时间:2024/05/29 05:57

之前在论坛里有人问的问题,使用Oracle实现,我用SQL Server完成了,记下了,以后学习也做个参考。

问题:

/*
说明:这是一个序列化的数据,为了便于说明,添加了“序号”字段。
需求:求n行数据的和。
      比如:求序列中5行数据的和,
            第一次应该是求1,2,3,4,5行的sum(value);
            第二次应该是求2,3,4,5,6行的sum(value);
            第三次应该是求3,4,5,6,7行的sum(value);
            第四次应该是求5,6,7,8,9行的sum(value);
            ......
          以此类推,直到name的值改变为止。
*/
declare @amount int,@part int,@i int
set @amount = (select count(amount) from (select count(*) amount from test group by name)subquery)
set @part= (select count(*) from test)
set @i=1
while(@i< = @part-5+1)
begin
select sum(value) sum from test where number between @i and @i+4
and name = (select name from test where number = @i)
having count(*)=5;
set @i = @i+1;
end

原创粉丝点击