|
连续聚合
[code=sql]USE tempdb
IF OBJECT_ID('TEST') IS NOT NULL
DROP TABLE TEST; -->如果表TEST不为空,删除表
GO
CREATE TABLE TEST -->创建测试表,字段及类型如下
(
sdate date,
num int
);
GO
INSERT INTO TEST VALUES -->向表中插入数据
('2012-10-1','10'),
('2012-10-2','20'),
('2012-10-3','30'),
('2012-10-4','40'),
('2012-10-5','50');
GO
SELECT * FROM TEST -->表的结构如下
/*
sdate num
---------- -----------
2012-10-01 10
2012-10-02 20
2012-10-03 30
2012-10-04 40
2012-10-05 50
(5 行受影响)
*/
-------------------开始查询------------------
select sdate,num,
(
select SUM(num)
from TEST as a
where a.sdate <= b.sdate
) as num_sum
from TEST as b
-------------------运行结果------------------
/*
sdate num num_sum
---------- ----------- -----------
2012-10-01 10 10
2012-10-02 20 30
2012-10-03 30 60
2012-10-04 40 100
2012-10-05 50 150
(5 行受影响)
*/[/code] |
|