为什么使用GROUP BY获得此结果?

时间:2019-04-12 10:00:56

标签: mysql

我想要我的状态列表以及设备最后一次处于这种状态的时间。

因此,如果我使用此查询对数据库进行简短浏览:

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
...
...

下一步,我要分组:

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?

2 个答案:

答案 0 :(得分:2)

您可以使用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

答案 1 :(得分:0)

使用分组依据进行聚合

SELECT state, MIN(time_start), MAX(time_end)
FROM report_log
WHERE device_id = 5
GROUP B state