HI @leo dec ,
Welcome to Microsoft Q&A!
Based on Erland's query, please refer below and check whether it is working:
drop table if exists #t1, #halfhours
create table #t1
(id int, dt date,
time_in time(7),
time_out time(7))
insert into #t1 values(101, '2021-03-22','12:23','13:46')
insert into #t1 values(102, '2021-03-22','11:26','16:46')
insert into #t1 values(103, '2021-03-22','14:50','15:25')
insert into #t1 values(104, '2021-03-22','12:23','13:46')
insert into #t1 values(105, '2021-03-23','14:49','16:55')
insert into #t1 values(106, '2021-03-23','15:25','18:00')
insert into #t1 values(107, '2021-03-24','16:05','18:27')
insert into #t1 values(108, '2021-03-24','10:14','18:30')
insert into #t1 values(109, '2021-03-24','11:05','15:02')
CREATE TABLE #halfhours (hh smalldatetime NOT NULL PRIMARY KEY);
INSERT #halfhours(hh)
SELECT dateadd(MINUTE, 30*(number-1), '20210322')
FROM master..spt_values WHERE TYPE = 'p'
and number >= 1
AND dateadd(MINUTE, 30*(number-1), '20210322') < '20210325';
;with cte as (
SELECT convert(date, h.hh) date,convert(time(0), h.hh) period, COUNT(*) count
FROM #halfhours h
JOIN #t1 t ON convert(date, h.hh) = t.dt
AND convert(time(0), h.hh) BETWEEN t.time_in AND dateadd(minute, 29, t.time_out)
GROUP BY h.hh)
,cte1 as (
select distinct convert(time(0), a.hh) hour,b.date,b.count from #halfhours a
inner join cte b on convert(time(0), a.hh)=b.period)
select * from
(select * from cte1) s
pivot
(max(count) for date in ([2021-03-22],[2021-03-23],[2021-03-24])) p
Output:
hour 2021-03-22 2021-03-23 2021-03-24
10:30:00 NULL NULL 1
11:00:00 NULL NULL 1
11:30:00 1 NULL 2
12:00:00 1 NULL 2
12:30:00 3 NULL 2
13:00:00 3 NULL 2
13:30:00 3 NULL 2
14:00:00 3 NULL 2
14:30:00 1 NULL 2
15:00:00 2 1 2
15:30:00 2 2 2
16:00:00 1 2 1
16:30:00 1 2 2
17:00:00 1 2 2
17:30:00 NULL 1 2
18:00:00 NULL 1 2
18:30:00 NULL NULL 2
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.