日期:2014-05-17  浏览次数:20411 次

SQL语句,望大神帮忙
表:date 字段表示时间。
num date
3 2013-07-01 00:00:00
5 2013-07-01 00:01:01
1 2013-07-01 00:04:30
3 2013-07-01 00:10:40
7 2013-07-01 00:12:00
8 2013-07-01 00:15:43
3 2013-07-01 00:22:00

需要:从现在开始,往前追溯,每各1个小时计算num字段的和

------解决方案--------------------

with tb(num,date)as(
select 3,'2013-07-01 01:00:00' union
select 5,'2013-07-01 02:01:01' union
select 1,'2013-07-01 03:04:30' union
select 3,'2013-07-01 05:10:40' union
select 7,'2013-07-01 07:12:00' union
select 8,'2013-07-01 09:15:43' union
select 3,'2013-07-01 16:22:00' 
)
,tc as(
select number,num from tb right join master..spt_values a
on DATEPART(hh,date)=a.number
where type='p' and number between 0 and 23 
)
select b.number,isnull(SUM(a.num),0) from tc a,tc b where a.number<=b.number
group by b.number
order by 1

这种效果?
------解决方案--------------------
create table t
(num int identity(1,1),[date] datetime)

insert into t([date])values(getdate())
insert into t([date])values(getdate())
insert into t([date])values(getdate())
insert into t([date])values(getdate())
insert into t([date])values(dateadd(dd,-1,getdate()))
insert into t([date])values(dateadd(dd,-1,getdate()))
insert into t([date])values(dateadd(dd,-1,getdate()))

select cast(YEAR([date]) as varchar)+'-'+cast(MONTH([date]) as varchar)+'-'+cast(DAY([date]) as varchar) as [date],SUM(num)
from t
group by YEAR([date]),MONTH([date]),DAY([date])
------解决方案--------------------
需求描述:统计各小时内的num合计值

sql语句:
select conver(char(14),日期字段,120),sum(num)
from table1
group by conver(char(14),日期字段,120)
order by conver(char(14),日期字段,120) desc

------解决方案--------------------