简体   繁体   English

在mySql中获得最大值的时间

[英]get time for max value in mySql

Table

+-------------------+------+
| Time              | value| 
+-------------------+------+
| 2011-2-1 1:01:00  | 10.1 |
+-------------------+------+
| 2011-2-1 1:03:15  | 7.7  |
+-------------------+------+
| 2011-2-1 1:05:21  | 5.4  |
+-------------------+------+
| 2011-2-1 1:06:00  | 2.3  |
+-------------------+------+
| 2011-2-1 1:09:30  | 4.2  |
+-------------------+------+
| 2011-2-1 1:11:10  | 6.2  |
+-------------------+------+

I want to get the maximum value for every 5 minutes. 我想获得每5分钟的最大值。 For example, 例如,

  • In the first 5 minutes, the maximum value is 10.1 在前5分钟内,最大值为10.1

  • In the second 5 minutes, the max value is 4.2 在接下来的5分钟内,最大值为4.2

In additional, I would also like to get the corresponding 'Time' for each maximum value. 另外,我还想为每个最大值获取相应的“时间”。

Many thanks 非常感谢

Your select statement needs to group all time by 5 minute intervals and then have a max() on value. 您的select语句需要将所有时间按5分钟间隔进行分组,然后将max()设为on。

This talks about grouping time in MySQL: 讨论MySQL中的分组时间:

http://forums.mysql.com/read.php?20,131939,131955#msg-131955 http://forums.mysql.com/read.php?20,131939,131955#msg-131955

To do the five minute grouping, use the round() function in combination with unix_timestamp() 要进行五分钟分组,请结合使用round()函数和unix_timestamp()

For five minutes: 五分钟:

round(unix_timestamp([time_field]) / 300)

So all together, your select might look like this (untested): 综上所述,您的选择可能看起来像这样(未经测试):

select
     round(unix_timestamp([time_field]) / 300) as Time,
     max(value) as Value
from
     [table_name]
group by
     round(unix_timestamp([time_field]) / 300)

A few different ways of doing this. 几种不同的方法可以做到这一点。

One that should work most of the time: 大多数情况下应该起作用的一种:

SELECT `Time`,`value`
FROM (SELECT `Time`,`value` FROM table ORDER BY `value` DESC) t2
GROUP BY UNIX_TIMESTAMP(`Time`) DIV 300

This relies on the fact that MySQL usually picks the first row it finds and returns that in light of the group by. 这取决于MySQL通常会选择找到的第一行并根据group by返回它。 So the inner query that first orders it by value, ensures the largest value is always found first. 因此,内部查询首先按值对其进行排序,以确保始终首先找到最大值。 (But its not totally reliable, as the mysql optimizer could end up arranging the query differently. Its not actully defined which row should be returned. (但是它并不完全可靠,因为mysql优化器最终可能会以不同的方式安排查询。它没有明确定义应返回哪一行。

If that doesn't work for you, try searching for the Max-group-concat trick. 如果这不适合您,请尝试搜索Max-group-concat技巧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM