获取按日期时间按小时分组的最高值记录

时间:2014-10-27 15:55:49

标签: mysql time-series greatest-n-per-group

我认为

中描述的常见案例的变体

Get records with highest/smallest <whatever> per group

这是包含数据的表

id  | value1 | value2 | curdate    | curtime
 1  |    234 |    500 | 2014-10-27 | 12:00:00
 2  |    200 |    400 | 2014-10-27 | 12:05:00
 3  |    300 |    600 | 2014-10-27 | 12:10:00
 4  |    400 |    800 | 2014-10-27 | 12:15:00
 5  |    150 |    700 | 2014-10-27 | 12:20:00
 ...
10  |    134 |    530 | 2014-10-27 | 13:00:00
12  |    220 |    420 | 2014-10-27 | 13:05:00
13  |    330 |    630 | 2014-10-27 | 13:10:00
14  |    440 |    840 | 2014-10-27 | 13:15:00
15  |    120 |    750 | 2014-10-27 | 13:20:00

我想要一份每小时最大值2的报告和相应的值1:

value1 | value2 | curdate    | curtime
   400 |    800 | 2014-10-27 | 12:00:00
   440 |    840 | 2014-10-27 | 13:00:00

我试图应用&#34;标准&#34;在上面的答案中指定的解决方案,但没有成功。使用MySQL。

SELECT t1.*
FROM Table AS t1
LEFT OUTER JOIN `Table` AS t2
ON t1.GroupId = t2.GroupId AND t1.OrderField < t2.OrderField
WHERE t2.GroupId IS NULL

我尝试过类似的事情:

SELECT t1.*
FROM Table AS t1
LEFT OUTER JOIN Table AS t2
ON SUBSTR(CONCAT(t1.curdate, ' ', t1.curtime), 1, 13) = SUBSTR(CONCAT(t2.curdate, ' ', t2.curtime), 1, 13) AND t1.value2 < t2.value2
WHERE ???? IS NULL   <--- not sure what to put here

请帮忙。感谢。

1 个答案:

答案 0 :(得分:1)

示例数据:

CREATE TABLE t
    (`id` int, `value1` int, `value2` int, `curdate` date, `curtime` time)
;

INSERT INTO t
    (`id`, `value1`, `value2`, `curdate`, `curtime`)
VALUES
    (1, 234, 500, '2014-10-27', '12:00:00'),
    (2, 200, 400, '2014-10-27', '12:05:00'),
    (3, 300, 600, '2014-10-27', '12:10:00'),
    (4, 400, 800, '2014-10-27', '12:15:00'),
    (5, 150, 700, '2014-10-27', '12:20:00'),
    (10, 134, 530, '2014-10-27', '13:00:00'),
    (12, 220, 420, '2014-10-27', '13:05:00'),
    (13, 330, 630, '2014-10-27', '13:10:00'),
    (14, 440, 840, '2014-10-27', '13:15:00'),
    (15, 120, 750, '2014-10-27', '13:20:00')
;

查询:

SELECT t.*
FROM t
INNER JOIN (
    SELECT
    DATE_FORMAT(CONCAT(curdate, ' ', curtime), '%Y-%m-%d %h') AS datehour,
    MAX(value2) as maxv2
    FROM
    t
    GROUP BY datehour
) sq ON t.value2 = sq.maxv2 AND DATE_FORMAT(CONCAT(t.curdate, ' ', t.curtime), '%Y-%m-%d %h') = sq.datehour;

结果:

+------+--------+--------+------------+----------+
| id   | value1 | value2 | curdate    | curtime  |
+------+--------+--------+------------+----------+
|    4 |    400 |    800 | 2014-10-27 | 12:15:00 |
|   14 |    440 |    840 | 2014-10-27 | 13:15:00 |
+------+--------+--------+------------+----------+