在MySQL中获取特定时间段内的最大值

时间:2014-11-07 05:02:47

标签: mysql

我有一张这样的桌子(tblFuel):

time                    fuel
2014-11-04 17:11:08     231
2014-11-04 17:34:16     254
2014-11-04 18:03:48     241
2014-11-04 18:41:34     137
2014-11-04 18:43:42     111

现在我希望每1小时显示最大的燃油价值。例如:最大值从17:00:00到17:59:59,依此类推。并按照以前的要求,预期结果应该:

time                    fuel
2014-11-04 17:34:16     254
2014-11-04 18:03:48     241

那么我该怎么做才能达到这个效果呢?

3 个答案:

答案 0 :(得分:2)

create table tblFuel (time timestamp, fuel int);

insert into tblFuel values ('2014-11-04 17:11:08', 231);
insert into tblFuel values ('2014-11-04 17:34:16', 254);
insert into tblFuel values ('2014-11-04 18:03:48', 241);
insert into tblFuel values ('2014-11-04 18:41:34', 137);
insert into tblFuel values ('2014-11-04 18:43:42', 111);

select
   *
from tblFuel
where concat(date(time), hour(time), fuel) in
    (select
       concat(date(time), hour(time), max(fuel))
     from tblFuel
     group by
        date(time),
        hour(time))

返回:

time                 fuel
2014-11-04 17:34:16  254
2014-11-04 18:03:48  241

答案 1 :(得分:0)

这是一种方法。它使用DATE_FORMAT函数按日期和小时进行分组。

SELECT ft.time, ft.fuel

FROM   fuel_table ft

       JOIN
       (SELECT DATE_FORMAT(time, '%Y%m%d %H') date_and_hour, MAX(fuel) max_fuel
        FROM   fuel_table
        GROUP BY date_and_hour) AS max_fuel
        ON DATE_FORMAT(ft.time, '%Y%m%d %H') = max_fuel.date_and_hour 
        AND ft.fuel = max_fuel

答案 2 :(得分:0)

此查询会有所帮助。

 DECLARE @tblFuel TABLE
(
    Val INTEGER,
    Time DATETIME
)

INSERT INTO @tblFuel  

SELECT '231', '2014-11-04 17:11:08' union All
SELECT '254', '2014-11-04 17:34:16' union All
SELECT '241', '2014-11-04 18:03:48' union All
SELECT '137', '2014-11-04 18:41:34' union All
SELECT '111', '2014-11-04 18:43:42'  

SELECT A.Val, A.Time FROM @tblFuel AS A 
Inner join 
(SELECT MAX(Val) AS VAL,  
        CONVERT(VARCHAR(20), Time, 110) +' ' + CAST(DATEPART(hour, Time) as varchar(2)) AS Time 
 FROM @tblFuel GROUP BY CONVERT(VARCHAR(20), Time, 110) +' ' + CAST(DATEPART(hour, Time) as varchar(2))) AS B
ON A.Val = B.val AND  CONVERT(VARCHAR(20), A.Time, 110) +' ' + CAST(DATEPART(hour, A.Time) as varchar(2)) = B.Time