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

 

转载于:https://www.cnblogs.com/aaronguo/p/11077756.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值