日期:2014-05-19  浏览次数:20518 次

求一SQL:以天为单位,之前所有数据累加
现有一数据表,每天记录都有记录时间,精确到秒。
现在想得到一个统计图。图以天为单位,得到每天及之前所有日期内记录项总和。

如果用group分组,再用聚合函数count(*)来统计,得到的是每天记录的累加,而不是这一天之前所有数据的累加。

望大家指点指点。谢谢。

------解决方案--------------------
declare @t table(date datetime)
insert @t select '2007-07-18 11:22:56 '
union all select '2007-07-18 12:22:56 '
union all select '2007-07-18 13:22:56 '
union all select '2007-07-18 14:22:56 '
union all select '2007-07-19 11:22:56 '
union all select '2007-07-19 12:22:56 '
union all select '2007-07-19 13:22:56 '
union all select '2007-07-19 14:22:56 '
union all select '2007-07-19 15:22:56 '
union all select '2007-07-20 11:22:56 '
union all select '2007-07-20 12:22:56 '


select date = convert(varchar(10), a.date, 120), total = max(a.total)
from
(select date,
total = (select count(1) from @t where date <= t.date)
from @t t) a
group by convert(varchar(10), a.date, 120)

/*
date total
---------- -----------
2007-07-18 4
2007-07-19 9
2007-07-20 11

(所影响的行数为 3 行)
*/
------解决方案--------------------
----try

select convert(char(10),时间,120),
sum(值)+isnull((select sum(值) from 表 b where convert(char(10),b.时间,120) <convert(char(10),a.时间,120)),0)
from 表 a
------解决方案--------------------
declare @t table(date datetime)
insert @t select '2007-07-18 11:22:56 '
union all select '2007-07-18 12:22:56 '
union all select '2007-07-18 13:22:56 '
union all select '2007-07-18 14:22:56 '
union all select '2007-07-19 11:22:56 '
union all select '2007-07-19 12:22:56 '
union all select '2007-07-19 13:22:56 '
union all select '2007-07-19 14:22:56 '
union all select '2007-07-19 15:22:56 '
union all select '2007-07-20 11:22:56 '
union all select '2007-07-20 12:22:56 '


select [天]=convert(varchar(10),date,120),[天记录]=count(*),
[总和]=(select count(1) from @t where convert(varchar(10),date,120)!> convert(varchar(10),t.date,120))
from @t t
group by convert(varchar(10),date,120)

(所影响的行数为 11 行)

天 天记录 总和
---------- ----------- -----------
2007-07-18 4 4
2007-07-19 5 9
2007-07-20 2 11

(所影响的行数为 3 行)