首页 > 解决方案 > 为什么我使用 GROUP BY 得到这个结果?

问题描述

我想要一份我的状态列表以及我的设备上次处于此状态的时间。

因此,如果我使用此查询简要查看我的数据库:

SELECT state, time_start, time_end
FROM report_log
WHERE device_id = 5
ORDER BY time_end DESC

结果是:

state | time_start            | time_end
---------------------------------------------------
1     |  2019-04-12 10:47:09  |  2019-04-12 11:30:10
4     |  2019-04-12 10:45:09  |  2019-04-12 10:46:09
5     |  2019-04-11 09:37:49  |  2019-04-12 10:46:09
1     |  2019-04-12 08:37:07  |  2019-04-12 10:44:09
5     |  2019-04-11 09:37:49  |  2019-04-12 09:51:08
5     |  2019-04-11 09:37:49  |  2019-04-12 08:58:08
4     |  2019-04-12 08:33:07  |  2019-04-12 08:34:07
4     |  2019-04-12 08:33:07  |  2019-04-12 08:34:07
...
...

接下来我想 GROUP 这样:

SELECT state, time_start, time_end
FROM (
    SELECT state, time_start, time_end
    FROM report_log
    WHERE device_id = 5
    ORDER BY time_end DESC
) AS d
GROUP BY d.state

但结果是:

state | time_start            | time_end
---------------------------------------------------
1     |  2019-04-12 11:40:10  |  2019-04-12 11:44:10
2     |  2019-04-11 05:01:45  |  2019-04-11 10:00:49
4     |  2019-04-10 12:41:32  |  2019-04-10 14:00:33
5     |  2019-04-09 06:56:07  |  2019-04-09 06:57:07

为什么?

在第一个结果中,我可以看到我的设备状态为 4 的最后一刻是 2019-04-12 10:46:09?

标签: mysql

解决方案


您可以使用maxgroup by

SELECT state, max(time_start), max(time_end)
FROM report_log
WHERE device_id = 5
GROUP BY d.state
ORDER BY time_end DESC

推荐阅读