有一表
id 起始时间 截止时间 字段 A
1 2007-05-06 02:00:00 2007-05-07 04:03:00 XXX
2 2007-05-06 11:00:00 2007-05-06 12:30:00 XXX
3 2007-05-06 12:00:00 2007-05-06 12:30:00 XXX
3 2007-05-07 12:00:00 2007-05-10 12:30:00 XXX
现在想分每天按小时 达到如下统计效果 需要根据字段A分组
2007-05-06的情况
小时段 count
0:00-1:00 0
1:00-2:00 1
2:00-3:00 1
3:00-4:00 1
4:00-5:00 1
5:00-6:00 1
......
11:00-12:00 2
12:00-13:00 3
......
22:00-23:00 1
23:00-24:00 1
2007-05-07的情况
小时段 count
0:00-1:00 0
1:00-2:00 0
2:00-3:00 1
3:00-4:00 1
4:00-5:00 1
5:00-6:00 0
......
11:00-12:00 0
12:00-13:00 1
......
22:00-23:00 1
23:00-24:00 1
------解决方案--------------------
建个辅助表。
create table tb (start_hour int,end_hour varchar(10),sec varchar(20))
insert into tb
select 0,0:59:59, '0:00-1:00 ' union all
select 1,1:59:59, '1:00-1:00 ' union all
....
select 23,23:59:59, '23:00-24:00 '
declare @s varchar(10)--输入查询日期
set @s= '2006-05-07 '
select count(a.*) as count,b.sec as 小时段 from table a inner join tb b on cast(@s+ ' '+b.end_hour as datetime) between and a.起始时间 and 截止时间