SQL按照顺序时间段统计



with cte as
(
select 
  cast(DATEADD(MINUTE,B.number*60,dateInfo.dday) as time) StartTime,
  cast(DATEADD(SECOND,-1,DATEADD(MINUTE,(B.number+1)*60,dateInfo.dday)) as time) EndTime 
from 
  (select top 1 convert(varchar(10),'00:00',120)  dday) dateInfo
  cross join master..spt_values b 
where b.type = 'P' and number <24 
)
select 
  DATENAME(HOUR, StartTime) AS [HOUR] ,  
  COUNT(SerialNo) AS Num
from
  (
   select StartTime,b.SerialNo
   from 
     cte dateInfo
     left join dbo.pd_SHFU b on cast(b.RecordTime as time) between StartTime and EndTime
     WHERE b.IsDelete=0 AND  DATEDIFF(DAY,b.RecordTime,GETDATE())=0 
  )a
group by   DATENAME(HOUR, StartTime)

由于工作需要,查阅资料后,总结并实践的代码如上。

借助master..spt_values表

按照时间(小时)划分统计时间段

 

 

你可能感兴趣的:(MSSQL)