如果您有开始时间:时间列
例10:10:01到10:10:31
需要按10个间隔进行分组:
示例
10:10:01 to 10:10:04 ,
10:10:04 to 10:10:07 ,
10:10:07 to 10:10:10 ,
10:10:10 to 10:10:13 ,
10:10:13 to 10:10:16 ,
10:10:16 to 10:10:19 ,
10:10:19 to 10:10:22 ,
10:10:22 to 10:10:25 ,
10:10:25 to 10:10:28 ,
10:10:28 to 10:10:31
使用SQL Server
答案 0 :(得分:2)
这是一个解决方案(SQL Fiddle demo):
declare @from time = '10:10:01', @to time = '10:10:31'
declare @interval int = datediff(millisecond, @from, @to) / 10
select dateadd(millisecond, @interval * (i-1), @from) as [From],
dateadd(millisecond, @interval * i, @from) as [To]
from (values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) x(i)
它是如何工作的:需要差异 - 以毫秒为单位进行良好测量,因为时间可能并不总是很好地划分 - 在指定的@from
和@to
之间,并除以10以获得间隔。然后它使用一个值表作为一个穷人的循环(因为我不想写出10个查询的UNION ALL
)来生成每个句点的时间和时间
答案 1 :(得分:0)
这是另一个解决方案,即使您更改了所需的间隔数量也能正常工作:
create function "dbo"."splitIntervals"
(
@starttime time
, @endtime time
, @intervals int
)
returns table
as
return
(
with cte as
(
select
cast( @starttime as time ) as "starttime"
, cast( dateadd( ms, datediff(ms, @starttime, @endtime) / @intervals, @starttime) as time ) as "endtime"
union all
select
cast(dateadd( ms, datediff(ms, @starttime, @endtime) / @intervals, "starttime") as time ) as "starttime"
, cast( dateadd( ms, datediff(ms, @starttime, @endtime) / @intervals, "endtime") as time ) as "entime"
from cte where "starttime" < cast( @endtime as time )
)
select
* from "cte"
where
endtime <= @endtime
);
;select * from "dbo"."splitIntervals" ( '10:10:01.000', '10:10:31.000', 15)