数据间隔为15分钟:
时间值 2010-01-01 00:15 3 2010-01-01 00:30 2 2010-01-01 00:45 4 2010-01-01 01:00 5 2010-01-01 01:15 1 2010-01-01 01:30 3 2010-01-01 01:45 4 2010-01-01 02:00 12 2010-01-01 02:15 13 2010-01-01 02:30 12 2010-01-01 02:45 14 2010-01-01 03:00 15 2010-01-01 03:15 3 2010-01-01 03:30 2 2010-01-01 03:45 3 2010-01-01 04:00 5 ..... ..... ..... 2010-01-02 00:00
通常会有96分。
根据这些值,我们可能会注意到从00:15到01:45的值彼此接近,从02:00到03:00的值彼此接近,而从03:15到04:00他们彼此靠近。
基于“彼此靠近”规则,我希望将数据“分为”三个部分:
请注意,数据可以是随机数据,并且可以根据上述规则分为3个以上的部分,但最大值不能超过10个部分。并且分组必须遵循时间顺序,例如,您不能将00:15/02:30/04:45分为1组,因为这3点不是连续的。
请考虑一下如何在t-sql中实现它。
已更新: 值可能是:
时间值 2010-01-01 00:15 3 2010-01-01 00:30 2 2010-01-01 00:45 4 2010-01-01 01:00 5 2010-01-01 01:15 1 2010-01-01 01:30 3 2010-01-01 01:45 4 2010-01-01 02:00 12 2010-01-01 02:15 13 2010-01-01 02:30 4-突然减少 2010-01-01 02:45 14 2010-01-01 03:00 15 2010-01-01 03:15 3 2010-01-01 03:30 2 2010-01-01 03:45 3 2010-01-01 04:00 5 ..... ..... ..... 2010-01-02 00:00
对于这种情况,我们不应该将02:30单独分组,因为我们希望组的大小必须至少为3分,并将该点(02:30)放到上一个分组(从02:00到03:00)。
由于您的问题发生了很大的变化,因此这里是新问题的新答案,我只包含了代码部分。
declare @t table(time datetime, value int) declare @variation float set @variation = 2 set nocount on insert @t values('2010-01-01 00:15',3) insert @t values('2010-01-01 00:30',2) insert @t values('2010-01-01 00:45',4) insert @t values('2010-01-01 01:00',5) insert @t values('2010-01-01 01:15',1) insert @t values('2010-01-01 01:30',3) insert @t values('2010-01-01 01:45',4) insert @t values('2010-01-01 02:00',52) insert @t values('2010-01-01 02:15',5) insert @t values('2010-01-01 02:30',52) insert @t values('2010-01-01 02:45',54) insert @t values('2010-01-01 03:00',55) insert @t values('2010-01-01 03:15',3) insert @t values('2010-01-01 03:30',2) insert @t values('2010-01-01 03:45',3) insert @t values('2010-01-01 04:00',5) declare @result table(mintime datetime, maxtime datetime) a: delete @result ;with t as ( select *, rn = row_number() over(order by time), log(value) lv from @t where datediff(day, time, '2010-01-01') = 0 ), a as ( select time, lv, rn, 0 grp from t where rn = 1 union all select t1.time, a.lv, t1.rn, case when exists (select 1 from t t2 where t1.rn between rn + 1 and rn + 3 and lv between t1.lv - @variation and t1.lv +@variation) then grp else grp + 1 end from t t1 join a on t1.rn = a.rn +1 ) insert @result select min(time), max(time) from a group by grp if @@rowcount > 10 begin set @variation=@variation + .5 goto a end select * from @result
结果:
mintime maxtime 2010-01-01 00:15:00.000 2010-01-01 01:45:00.000 2010-01-01 02:00:00.000 2010-01-01 03:00:00.000 2010-01-01 03:15:00.000 2010-01-01 04:00:00.000