您的位置:首页 > 数据库

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

2012-04-13 10:19 323 查看
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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: