问题
I have a table, table_1, which has data for EACH minute and looks like:
+---------------------+---------+
| 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 |
+---------------------+---------+
I wish to fetch hourly min and max values. Something like:
+---------------------+---------+
| date_time | value |
+---------------------+---------+
| 2015-06-05 18:10:00 | 200.663 |
| 2015-06-05 18:45:00 | 222.749 |
| 2015-06-05 19:10:00 | 190.957 |
| 2015-06-05 19:33:00 | 400.063 |
+---------------------+---------+
Currently I am creating a for loop in PHP and runs a query for EACH hour. However, it is obviously not the best way to do it, and is thus VERY TIME CONSUMING. For example:
for($temp = $st; $temp <= $et; $temp = $temp + 60){//looping for each hour
$sql1 = "select * from table_1 where value in
(select max(value) from table_1
where date_time >= '".date('Y-m-d H:i:s',$st)."'
and date_time < '".date('Y-m-d H:i:s',$temp)."' )
and date_time >= '".date('Y-m-d H:i:s',$st)."'
and date_time < '".date('Y-m-d H:i:s',$temp)."' limit 1";
$rs1 = mysql_query($sql1);
$row1 = mysql_fetch_assoc($rs1)
$val1 = $row1['value'];
$date1 = $row1['date_time'];
}
回答1:
Anawer for the question
select DATE_FORMAT(date_time,'%Y-%m-%d %H:00:00') h, min(value), max(value)
from thetable
group by h
1. How to do the same thing for intervals like 6 hours or 15 minutes.
for 15 minute interval:
select date_time, min(value), max(value)
from t1
group by round(unix_timestamp(date_time)/(15 * 60))
For 6 hours interval change to (6 * 60 * 60)
2. The result above does NOT show the original time stamp corresponding to the min and max values. How to get those.
Such query give you what you want. But if, for example, there are some minimum values in an interval, get so many rows how many such values
select date_time, value
from t1,
(select DATE_FORMAT(date_time,'%Y-%m-%d %H:00:00') h,
min(value) min, max(value) max
from t1
group by h
) t
where value in (min, max)
and DATE_FORMAT(date_time,'%Y-%m-%d %H:00:00') = h
来源:https://stackoverflow.com/questions/32421110/aggregating-mysql-data-on-hourly-basis-from-minute-wise-raw-data