22,301
社区成员




create table states([id] int,[time] datetime)
insert into states([id],[time])
select 1,'2017-06-21 14:58:02.000' union all
select 2,'2016-11-24 23:35:16.000' union all
select 3,'2017-04-24 11:12:38.000' union all
select 4,'2016-12-10 10:09:07.000' union all
select 5,'2017-06-19 14:53:30.000' union all
select 6,'2016-12-09 15:34:45.000' union all
select 7,'2017-04-24 11:41:46.000'
declare @begindate datetime,@enddate datetime
select @begindate='2016-06-02',
@enddate='2017-07-02'
select [timerange]=rtrim(t.st)+'点到'+rtrim(t.et)+'点',
[qty]=isnull(u.qty,0)
from (select 'st'=a.number,
'et'=a.number+2
from master.dbo.spt_values a
where a.type='P'
and a.number between 0 and 22
and a.number%2=0) t
outer apply(select qty=count(1)
from states b
where b.[time] between @begindate and @enddate
and datepart(hh,b.[time]) between t.st and t.et) u
/*
timerange qty
------------------------------ -----------
0点到2点 0
2点到4点 0
4点到6点 0
6点到8点 0
8点到10点 1
10点到12点 3
12点到14点 2
14点到16点 3
16点到18点 0
18点到20点 0
20点到22点 0
22点到24点 1
(12 row(s) affected)
*/
with states(id,[time]) as(
select 1,'2017-06-21 14:58:02.000' union all
select 2,'2016-11-24 23:35:16.000' union all
select 3,'2017-04-24 11:12:38.000' union all
select 4,'2016-12-10 10:09:07.000' union all
select 5,'2017-06-19 14:53:30.000' union all
select 6,'2016-12-09 15:34:45.000' union all
select 7,'2017-04-24 11:41:46.000'
)
select (number-1)*2 [start],number*2 [end],sum(case when datename(hour,[time]) between (number-1)*2 and number*2 then 1 else 0 end) [ct] from states,master..spt_values where [time] between '2016-07-02' and '2017-06-02'
and type='p' and number between 1 and 12 group by (number-1)*2,number*2