【原创】SQL数据累计求和等聚合操作

if Object_id('tb1') is not null Drop table tb1;
go
create table tb1(date int primary key, sale int);
go
insert into tb1(date, sale)
select 1, 20 union all
select 2, 15 union all
select 3, 14 union all 
select 4, 18 union all 
select 5, 30;

select * from tb1;

--方法一,单个聚合
select date, sale, (select sum(sale) from tb1 b where b.date <= a.date) as [sum]
from tb1 a;

--方法二,多个聚合时 select a.date, a.sale, sum(b.sale) as [sum] from tb1 a join tb1 b on b.date <= a.date group by a.date, a.sale; /* --查询结果 date sale sum ----------- ----------- ----------- 1 20 20 2 15 35 3 14 49 4 18 67 5 30 97 */
posted on 2012-04-13 10:19  唐朝t  阅读(2740)  评论(0编辑  收藏  举报