sql查询求和问题(sqlserver2008r2)
有这样一张表
table A
字段
code varchar(20),
tv datetime,
value varchar(20)
数据则是如下:
CODE TV VALUE
2000 2013-12-05 00:00:00.000 0.5
2000 2013-12-06 00:00:00.000 1.5
2000 2013-12-07 00:00:00.000 2.3
2000 2013-12-08 00:00:00.000 0.4
2000 2013-12-09 00:00:00.000 4.1
2000 2013-12-10 00:00:00.000 0.1
如何用sql得到以下的数据?
CODE TV VALUE SUM
2000 2013-12-05 00:00:00.000 0.5 0.5+1.5+2.3
2000 2013-12-06 00:00:00.000 0.5 1.5+2.3+0.4
2000 2013-12-07 00:00:00.000 0.5 2.3+0.4+4.1
2000 2013-12-08 00:00:00.000 0.5 0.4+4.1+0.1
SUM这一列的含义是 取当前行数据时间及其后两天的行数据的VALUE值之和
另外,数据条数会减少一些,因为2013-12-09日的数据没有了11日的数据后无法计算 只需要计算到09日即可 这个时间可以显示的设置(意思就是最终的sql中可以加上tv<=2013-12-08)
不知道这种求和函数怎么写。要求只用SQL,不能用存储过程之类的
[解决办法]
create table tableA(code varchar(20),
tv datetime,
value numeric(10,1)
)
insert into tableA
select 2000,'2013-12-05 00:00:00.000',0.5
union all select 2000,'2013-12-06 00:00:00.000',1.5
union all select 2000,'2013-12-07 00:00:00.000',2.3
union all select 2000,'2013-12-08 00:00:00.000',0.4
union all select 2000,'2013-12-09 00:00:00.000',4.1
union all select 2000,'2013-12-10 00:00:00.000',0.1
go
select *,[sum]=(select sum(VALUE) from tableA b where b.tv>=a.tv and b.tv<=dateadd(day,2,a.tv))
from tableA a
where tv<='2013-12-08'
drop table tableA
/*
code tv value sum
----------------------------------------------------
20002013-12-05 00:00:00.000.54.3
20002013-12-06 00:00:00.0001.54.2
20002013-12-07 00:00:00.0002.36.8
20002013-12-08 00:00:00.000.44.6
*/
select code,
tv,
value,
(SELECT sum(cast(isnull(VALUE, 0) as decimal(10, 3)))
FROM A as I
WHERE DATEDIFF(day, O.tv, I.tv) >= 0
and DATEDIFF(day, O.tv, I.tv) <= 2) as sumvalue
from A as O