2016-10-13 41 views
1

我试图构建一个查询,按定时间隔(即30分钟)对我的数据进行分组,然后计算每组中的第一行和最后一行之间的差异。按时间间隔分组,包括下一个开始?

select (max(v) - min(v)) as x, from_unixtime(FLOOR(UNIX_TIMESTAMP(d)/(30*60))*(30*60)) as timeKey from y group by timeKey

但是我需要以某种方式调整它包括12:00 and 12:30而非12:00 and 12:29之间的一切以上正确返回我的30分钟块数据。

我曾尝试使用以下内容,但在分配值时不能使用max

select max(v) - @lastV, from_unixtime(FLOOR(UNIX_TIMESTAMP(d)/(30*60))*(30*60)) as timeKey, @lastv := v from `test`, (select @lastV:=0) lastV group by timeKey

http://sqlfiddle.com/#!9/e8d74/4

我已经与一些数据,可以被用作一个例子中创建的上述SQL小提琴。

有没有人有任何建议?

+4

然后你会得到重复的条目。 '12:30'将在12:00-12:30和12:30-13:00之间。你想要哪一个? – sagi

+0

@sagi - 对不起,觉得我没有适当的回应 - 我试图复制目前通过代码处理的过程,它通过间隔循环并执行查询,即'(select max(v) - min(v)as usage from'test'where d在'2016-01-01 12:00'和'2016-01-01 12:30'之间,这有帮助吗? – Gavin

回答

0

,我设法想出这个早上的潜在解决方案:

select *, IF(@lastV, @lastV - minV, 0) as `usage`, @lastV := minV from ( select min(v) as minV, max(v) as maxV, from_unixtime(FLOOR(UNIX_TIMESTAMP(d)/(30*60))*(30*60)) as timeKey from `test` group by timeKey order by timeKey desc ) items, (select @lastV:=0) lastV

http://sqlfiddle.com/#!9/e8d74/18/0

它可惜只排序下降时工作并产生冗余行(第一行有没有什么比较)但是根据我的测试,这一行不是必需的,在读取数据时可以忽略。

如果任何人有任何其他解决方案,会有用吗?