您好,这是我的解决方法。
我用您的数据创建了一个表“测试”。
首先我得到最小和最大间隔,然后,我用 CTE 得到这些值之间的所有间隔。
最后,通过这个 CTE 和一个左连接以及 time_start 和 time_end 之间的间隔,我得到了答案。
这是1小时的间隔
DECLARE @minDate AS DATETIME;
DECLARE @maxDate AS DATETIME;
SET @minDate = (select case
when (select min(time_start) from test) < (select min(time_end) from test)
then (select min(time_start) from test)
else (select min(time_end) from test) end )
SET @minDate = FORMAT(@minDate, 'dd-MM.yyyy HH:00:00')
SET @maxDate = (select case
when (select max(time_start) from test) > (select max(time_end) from test)
then (select max(time_start) from test)
else (select max(time_end) from test) end )
SET @maxDate = FORMAT(@maxDate, 'dd-MM.yyyy HH:00:00')
;WITH Dates_CTE
AS (SELECT @minDate AS Dates
UNION ALL
SELECT Dateadd(hh, 1, Dates)
FROM Dates_CTE
WHERE Dates < @maxDate)
SELECT d.Dates as time_interval, count(*) as row_count
FROM Dates_CTE d
LEFT JOIN test t on d.Dates
between (FORMAT(t.time_start, 'dd-MM.yyyy HH:00:00'))
and (FORMAT(t.time_end, 'dd-MM.yyyy HH:00:00'))
GROUP BY d.Dates
对于 10 分钟的间隔,您需要进行一些更改。
首先我格式化日期得到分钟(dd-MM.yyyy HH:mm:00 instead of dd-MM.yyyy HH:00:00)
在左侧连接中,我接近 time_start 和 time_end 到他们的 10 分钟时间(9:30:00 中的 9:32:00)(dateadd(minute, 10 * (datediff(minute, 0, time_start) / 10), 0)):
DECLARE @minDate AS DATETIME;
DECLARE @maxDate AS DATETIME;
SET @minDate = (select case
when (select min(time_start) from test) < (select min(time_end) from test)
then (select min(time_start) from test)
else (select min(time_end) from test) end )
SET @minDate = FORMAT(@minDate, 'dd-MM.yyyy HH:mm:00')
SET @maxDate = (select case
when (select max(time_start) from test) > (select max(time_end) from test)
then (select max(time_start) from test)
else (select max(time_end) from test) end )
SET @maxDate = FORMAT(@maxDate, 'dd-MM.yyyy HH:mm:00')
;WITH Dates_CTE
AS (SELECT @minDate AS Dates
UNION ALL
SELECT Dateadd(minute, 10, Dates)
FROM Dates_CTE
WHERE Dates < @maxDate)
SELECT d.Dates as time_interval, count(*) as row_count
FROM Dates_CTE d
LEFT JOIN test t on d.Dates
between dateadd(minute, 10 * (datediff(minute, 0, time_start) / 10), 0)
and dateadd(minute, 10 * (datediff(minute, 0, time_end) / 10), 0)
GROUP BY d.Dates
最后我每隔 1 小时得到这个结果:
+---------------------+-----------+
| time_interval | row_count |
+---------------------+-----------+
| 01/01/2019 08:00:00 | 1 |
| 01/01/2019 09:00:00 | 3 |
| 01/01/2019 10:00:00 | 2 |
| 01/01/2019 11:00:00 | 2 |
| 01/01/2019 12:00:00 | 1 |
| 01/01/2019 13:00:00 | 1 |
| 01/01/2019 14:00:00 | 1 |
| 01/01/2019 15:00:00 | 1 |
+---------------------+-----------+
我希望它对你有用。