select
sum(case when starttime <= 0 and endtime >= 0 then 1 else 0 end) '0-1',
sum(case when starttime <= 1 and endtime >= 1 then 1 else 0 end) '1-2',
sum(case when starttime <= 2 and endtime >= 2 then 1 else 0 end) '2-3'
from
(select a.roomid,a.userid,date_format(a.time,'%h') starttime, date_format(min(b.time),'%h') endtime
from room a, room b where a.roomid=b.roomid and a.userid=b.userid and a.type=1 and b.type=2
and b.time > a.time group by roomid,userid,starttime) tmp