Mysql:获取相应时间和分组的最大值

时间:2014-07-19 04:42:27

标签: mysql datetime max

我的表是:

timelog              | roomtemp  
2014-07-14 01:16:04  | 25.0    |
2014-07-14 02:14:05  | 26.0    |
2014-07-14 03:13:05  | 25.0    |
2014-07-14 05:13:11  | 29.0    |
2014-07-14 06:15:05  | 25.0    |
2014-07-14 07:17:13  | 30.0    |
       .
       .
2014-07-15 01:13:05  | 25.0    |
2014-07-15 01:16:04  | 31.0    |
2014-07-15 02:14:05  | 25.0    |
2014-07-15 03:13:05  | 28.0    |
2014-07-15 05:13:05  | 25.0    |

我希望每天获得相应时间日志的最大值(roomtemp) 如:

2014-07-14 07:17:13  | 30.0    |
2014-07-15 01:16:04  | 31.0    |

我厌倦了2014-07-14,但是失败了〜:

$sql="SELECT timelog, MAX(roomtemp) FROM $tablename WHERE timelog BETWEEN '2014-07-14 00:00:00' AND '2014-07-14 23:59:59' ";<p>
$result=mysqli_query($db, $sql) or die("ERR201: Error");

显示错误消息

如果删除SELECT

之后的时间日志,我可以获得最大的室内空间
$sql="SELECT MAX(roomtemp) FROM $tablename WHERE timelog BETWEEN '2014-07-14 00:00:00' AND '2014-07-14 23:59:59' ";<p>
$result=mysqli_query($db, $sql) or die("ERR201: Error");

我也尝试过DAY(timelog),但是timelog值不正确......

2 个答案:

答案 0 :(得分:2)

查询当天获取日间和最高温度:

select date(timelog) as day,max(roomtemp) from table_name group by day;

输出:

enter image description here

查询以获取一天的时间和最高温度:

SELECT timelog AS curr_day,MAX(roomtemp) FROM (SELECT * FROM day_temperature ORDER BY roomtemp DESC) c GROUP BY DATE(curr_day);

输出:

enter image description here

SQL转储:

/*
SQLyog Ultimate v10.00 Beta1
MySQL - 5.5.24-log 
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;

create table `day_temperature` (
    `timelog` datetime ,
    `roomtemp` float 
); 
insert into `day_temperature` (`timelog`, `roomtemp`) values('2014-07-19 10:27:20','25');
insert into `day_temperature` (`timelog`, `roomtemp`) values('2014-07-19 10:30:21','27');
insert into `day_temperature` (`timelog`, `roomtemp`) values('2014-07-20 11:10:20','28');
insert into `day_temperature` (`timelog`, `roomtemp`) values('2014-07-20 12:00:00','23');

答案 1 :(得分:0)

您可以使用DATE()从日期时间中提取日期:

SELECT DATE(timelog), MAX(room_temp) FROM $tablename GROUP BY DATE(timelog)