日期:2014-05-18  浏览次数:21006 次

如何从数据库中查询每5分钟的平均值?!
如何从数据库中查询每5分钟的平均值?!

  表结构      
    人数                                                           时间      
    1                                                                       2005-12-1       14:12:16      
    2                                                                       2005-12-1       14:22:16      
    3                                                                       2005-12-1       14:47:16      
    11                                                                   2005-12-1       14:36:16      
    12                                                                   2005-12-2       10:22:16      
    3                                                                       2005-12-2       10:23:16      
       
每天24个小时的每5分钟的平均值查询,然后根据这些平均值画曲线,曲线部分已经解决,关键一个问题是怎么算每5分的平均值!

------解决方案--------------------
--這樣可否?
select avg(人数)
from T
group by (datediff(minute, '2005-12-1 ', 时间)-1)/5
------解决方案--------------------
--创建测试数据
declare @tab2 table
(
人数 int,
时间 datetime
)

insert into @tab2 select 1, '2005-12-1 14:12:16 '
insert into @tab2 select 2, '2005-12-1 14:22:16 '
insert into @tab2 select 3, '2005-12-1 14:47:16 '
insert into @tab2 select 11, '2005-12-1 14:36:16 '
insert into @tab2 select 12, '2005-12-2 10:22:16 '
insert into @tab2 select 3, ' 2005-12-2 10:23:16 '


--解决方法
select min(时间) as 起始时间,dateadd(mi,5,min(时间)) as 终止时间,平均人数=avg(人数) from
(
select *,col=datediff(mi,(select min(时间) from @tab2 c where datediff(day,c.时间,b.时间)=0),时间)/5 from @tab2 b
) a
group by convert(varchar(10),时间,120),col
order by 1