SQL按照順序時間段統計


借助master..spt_values表

按照時間(半小時)划分統計時間段:

select 
  cast(DATEADD(MINUTE,B.number*30,dateInfo.dday) as time) StartTime,
  cast(DATEADD(SECOND,-1,DATEADD(MINUTE,(B.number+1)*30,dateInfo.dday)) as time) EndTime 
from 
  (select top 1 convert(varchar(10),'07:00',120)  dday) dateInfo
  cross join master..spt_values b 
where b.type = 'P' and number <24  

統計時間段(半小時)范圍內總數量:

with cte as
(
select 
  cast(DATEADD(MINUTE,B.number*30,dateInfo.dday) as time) StartTime,
  cast(DATEADD(SECOND,-1,DATEADD(MINUTE,(B.number+1)*30,dateInfo.dday)) as time) EndTime 
from 
  (select top 1 convert(varchar(10),'07:00',120)  dday) dateInfo
  cross join master..spt_values b 
where b.type = 'P' and number <24  
)
select 
  StartTime,
  EndTime,
  sum(PreSum) PreSum,
  sum(PreUsed) PreUsed
from
  (
   select StartTime,EndTime,case when hbStartTime is null then 0 else 1 end PreSum,case when Used ='1' then 0 else 1 end PreUsed
   from 
     cte dateInfo
     left join yshb_timetable b on cast(b.hbStartTime as time) between StartTime and EndTime
     where b.YshbID='查詢條件'
  )a
group by StartTime,EndTime

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM