A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Hi @leo dec ,
Welcome to Microsoft Q&A!
Please also refer below and check whether it is working.
create table #t( id int, start_Dt datetime, end_dt datetime)
insert into #t values (101, '2021-07-31 22:40:00.000','2021-08-01 01:23:00.000')
insert into #t values (102, '2021-08-01 11:40:00.000','2021-08-01 13:23:00.000')
insert into #t values (103, '2021-08-01 10:42:00.000','2021-08-01 17:15:00.000')
;WITH CTE AS (
SELECT MIN(CONVERT(datetime, CONVERT(varchar(13), start_Dt, 121) + ':00:00')) AS MIND,
MAX(CONVERT(datetime, CONVERT(varchar(13), end_dt, 121) + ':00:00')) AS MAXD
FROM #t)
,hrs AS (
select MIND dt from CTE
UNION ALL
SELECT DATEADD(HOUR, 1, dt) AS [Hour] FROM hrs ,CTE
WHERE dt < MAXD)
select isnull(d.cnt,0) cnt,a. dt from hrs a
left join (
select b.dt,
count(*) cnt from hrs b,#t c
where b.dt between CONVERT(datetime, CONVERT(varchar(13), start_Dt, 121) + ':00:00') and end_dt
group by b.dt) d
on a.dt=d.dt
Output:
cnt dt
1 2021-07-31 22:00:00.000
1 2021-07-31 23:00:00.000
1 2021-08-01 00:00:00.000
1 2021-08-01 01:00:00.000
0 2021-08-01 02:00:00.000
0 2021-08-01 03:00:00.000
0 2021-08-01 04:00:00.000
0 2021-08-01 05:00:00.000
0 2021-08-01 06:00:00.000
0 2021-08-01 07:00:00.000
0 2021-08-01 08:00:00.000
0 2021-08-01 09:00:00.000
1 2021-08-01 10:00:00.000
2 2021-08-01 11:00:00.000
2 2021-08-01 12:00:00.000
2 2021-08-01 13:00:00.000
1 2021-08-01 14:00:00.000
1 2021-08-01 15:00:00.000
1 2021-08-01 16:00:00.000
1 2021-08-01 17:00:00.000
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.