您的经期不规律(有些为 15 分钟,有些为 1 小时,有些为几个小时)。在这种情况下,您能做的最好的事情就是使用 case 语句运行查询:
with thetable as
(
SELECT 'TM' code, convert(datetime, '2011-04-15 07:01:00 AM') date, 1 id union all
SELECT 'TM', convert(datetime, '2011-04-15 07:05:00 AM'), 2 union all
SELECT 'TM', convert(datetime, '2011-04-15 07:08:00 AM'), 3 union all
SELECT 'TM', convert(datetime, '2011-04-15 07:20:00 AM'), 4 union all
SELECT 'TM', convert(datetime, '2011-04-15 08:25:00 AM'), 5
)
SELECT '07:00 - 07:15' interval, sum(case when CONVERT(varchar, date, 108) between '07:00:00' AND '07:14:59' then 1 else 0 end) counting
FROM thetable
union
select '07:15 - 08:00', sum(case when CONVERT(varchar, date, 108) between '07:15:00' AND '07:59:59' then 1 else 0 end)
from thetable
union
select '08:00 - 09:00', sum(case when CONVERT(varchar, date, 108) between '07:59:59' AND '08:59:59' then 1 else 0 end)
from thetable
现在,如果你确实有固定的间隔,你会做这样的事情:
select counting,
dateadd(ms,500-((datepart(ms,interval)+500)%1000),interval) intini
from
(
SELECT COUNT(1) counting, CONVERT(datetime, round(floor(CONVERT(float, date) * 24 * 4) / (24 * 4), 11)) interval
FROM
(
SELECT 'TM' code, convert(datetime, '2011-04-15 07:01:00 AM') date, 1 id union all
SELECT 'TM', convert(datetime, '2011-04-15 07:05:00 AM'), 2 union all
SELECT 'TM', convert(datetime, '2011-04-15 07:08:00 AM'), 3 union all
SELECT 'TM', convert(datetime, '2011-04-15 07:20:00 AM'), 4 union all
SELECT 'TM', convert(datetime, '2011-04-15 08:25:00 AM'), 5
) thetable
group by FLOOR(CONVERT(float, date) * 24 * 4)
) thetable2
请注意,24 * 4 是 15 分钟的间隔。如果你的时间间隔是 1 小时,你应该用 24 代替。如果你的时间间隔是 10 分钟,它应该是 24 * 6。我想你明白了。