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

求Sql 按 时间段来 集计数据 ??
id createtime xiaoshoushu 
----------- ------------------------------------------------------ ----------- 
1 2012-03-09 01:01:00.000 1
2 2012-03-09 01:02:00.000 2
3 2012-03-09 02:15:00.000 3
4 2012-03-09 03:01:00.000 5
5 2012-03-09 03:15:00.000 1
6 2012-03-09 05:15:00.000 3
7 2012-03-09 05:35:00.000 4
8 2012-03-09 05:45:00.000 3

假如 我表里 数据 是这样的  
我想 取得 时间带别的 xiaoshoushu 的 集计
就是 Createtime = 2012/03/09 的 零点到 一点 , 一点到两点,两点到三点,三点到四点,四点到五点,五点到六点,六点到七点,。。。。。。。。。。。。。。。 一直到 23点 到 24点 的 分别的 销售数  

望 大侠给 解答

------解决方案--------------------
SQL code

select convert(varchar(10),createtime,120) date,datepart(hh,createtime) hh,sum(xiaoshoushu) xiaoshu
from tb
where convert(varchar(10),createtime,120) = '2012-03-09'
group by convert(varchar(10),createtime,120),datepart(hh,createtime)

------解决方案--------------------
如果中间有缺省的也要统计进去,楼主可以自己设计一个对应时间段的临时表去left join主表,继而进行相应的统计。
------解决方案--------------------
SQL code
create table tb(id int,createtime datetime,xiaoshoushu int)
insert into tb select 1,'2012-03-09 01:01:00.000',1
insert into tb select 2,'2012-03-09 01:02:00.000',2
insert into tb select 3,'2012-03-09 02:15:00.000',3
insert into tb select 4,'2012-03-09 03:01:00.000',5
insert into tb select 5,'2012-03-09 03:15:00.000',1
insert into tb select 6,'2012-03-09 05:15:00.000',3
insert into tb select 7,'2012-03-09 05:35:00.000',4
insert into tb select 8,'2012-03-09 05:45:00.000',3
go
select convert(varchar(13),createtime,120),sum(xiaoshoushu)
from tb
group by convert(varchar(13),createtime,120)
/*
              
------------- -----------
2012-03-09 01 3
2012-03-09 02 3
2012-03-09 03 6
2012-03-09 05 10

(4 行受影响)

*/
go
drop table tb