首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求Sql 按 时间段来 集计数据 ?该怎么解决

2012-03-19 
求Sql按 时间段来 集计数据 ??idcreatetimexiaoshoushu----------- ------------------------------------

求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) xiaoshufrom tbwhere 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',1insert into tb select 2,'2012-03-09 01:02:00.000',2insert into tb select 3,'2012-03-09 02:15:00.000',3insert into tb select 4,'2012-03-09 03:01:00.000',5insert into tb select 5,'2012-03-09 03:15:00.000',1insert into tb select 6,'2012-03-09 05:15:00.000',3insert into tb select 7,'2012-03-09 05:35:00.000',4insert into tb select 8,'2012-03-09 05:45:00.000',3goselect convert(varchar(13),createtime,120),sum(xiaoshoushu)from tbgroup by convert(varchar(13),createtime,120)/*              ------------- -----------2012-03-09 01 32012-03-09 02 32012-03-09 03 62012-03-09 05 10(4 行受影响)*/godrop table tb 

热点排行