select cast(hour_ as varchar)+'点'+cast(hour_+1 as varchar)+'点' as 时段,
count(1) 访问次数
from 表名字,
(select 0 as hour_
union all select 1
union all select 2
union all select 3
union all select 4
union all select 5
union all select 6
union all select 7
union all select 8
union all select 9
union all select 10
union all select 11
union all select 12
union all select 13
union all select 14
union all select 15
union all select 16
union all select 17
union all select 18
union all select 19
union all select 20
union all select 21
union all select 22
union all select 23
)a
group by a.hour_
where a.hour_ between datepart(hh,开始访问时间) and datepart(hh,结束访问时间)
t表 简化了,楼主要修改一点点
create table t(s datetime,e datetime)
select cast(b.number as varchar)+'点~'+cast((b.number+1)%24 as varchar)+'点' as 时段,count(a.s) as 次数 from t a right join master..spt_values b on b.number between datepart(hh,s) and datepart(hh,e) where b.type='p' and b.number<=23
group by b.number
/*结果部分
时段 次数
------------------
0点~1点 0
。。。
23点~0点 0
*/
要注意的是0点,是算在起始的位置的 也就是每一个时段都是一个前闭后开区间
[0,1) 0
[1,2) 0
[2,3) 1
...
这样子的
学习