从分钟原始数据聚合mysql数据

时间:2015-09-06 17:50:29

标签: mysql group-by

我有一个表table_1,它有每分钟的数据,看起来像:

+---------------------+---------+
| date_time           | value   |
+---------------------+---------+
| 2015-06-05 18:00:00 | 222.663 |
| 2015-06-05 18:01:00 | 222.749 |
| 2015-06-05 18:02:00 | 222.957 |
| 2015-06-05 18:03:00 | 223.063 |
| 2015-06-05 18:04:00 | 223.117 |
+---------------------+---------+

我希望每15分钟间隔(或任何其他间隔;可自定义)获取最小值和最大值。 期望的输出:

+---------------------+---------+
| date_time           | value   |
+---------------------+---------+
| 2015-06-05 18:10:00 | 200.663 | (min between 18:00 and 18:14)
| 2015-06-05 18:13:00 | 222.749 | (max between 18:00 and 18:14)
| 2015-06-05 18:17:00 | 190.957 | (min between 18:15 and 18:29)
| 2015-06-05 18:33:00 | 400.063 | (max between 18:15 and 18:29)
+---------------------+---------+

我目前正在使用以下解决方案:

select date_time, value 
    from table_1, 
         (select date_time h, 
                 min(value) min, max(value) max 
              from table_1 where date_time >= '2015-06-05 18:00:00' and date_time < '2015-06-05 19:00:00' 
            group by round(unix_timestamp(date_time)/(15 * 60))
         ) t 
  where value in (min, max) 
    and date_time = h

解决方案基于: Aggregating MySQL data on hourly basis from minute-wise raw data

然而,目前的解决方案只给我两个值(一分钟和一个最大值)。我希望所有15分钟间隔内的所有最小值和最大值,如上图所示。

2 个答案:

答案 0 :(得分:1)

这是问题作者的常见结果:)

MapperProvider<T>.Instance

答案 1 :(得分:1)

以下代码段每隔15分钟给出最大值和最小值。你可以用完全除以60的任何整数替换15。

    select b.date_time,b.value
 from
 table_1 b
 join (select  min(a.value) minv, max(a.value) maxv, date_sub(a.date_time,INTERVAL second(a.date_time)+
                (minute(a.date_time)-minute(a.date_time) div 15)
                *60 second) partition_interval
from table_1 a
 group by partition_interval) temp
on temp.partition_interval=date_sub(b.date_time,INTERVAL second(b.date_time)+
                (minute(b.date_time)-minute(b.date_time) div 15)
                *60 second)
                and b.value in(temp.minv,temp.maxv)
group by temp.partition_interval,b.value

代码编辑1: 将@date_time替换为date_time

代码按期望给出结果。

请在http://sqlfiddle.com/#!9/bd668/16

核实