mysql - 为什么我使用 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?
解决方案
您可以使用max
和group 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
推荐阅读
- regex - "\S+?@\S+" 和 "\S+@\S+" 在正则表达式中给出相同的输出
- angular - Angular 7 终于不起作用了
- php - 如何在 PHP REST 网站中实现 RS512 或更高的安全算法?
- rust - 接受 HashMap 和 BtreeMap 的 Rust 函数
- angular - 我应该先制作 Angular Web 项目,然后将其转换为移动设备吗?
- ruby-on-rails - Rails 5:设计可邀请的添加自定义字段
- makefile - 如何修改 configure 或 configure.ac 脚本以仅在指定位置查找二进制文件
- angularjs - 如何从角度降序开始
- c++ - 模板类成员与非成员模板函数的歧义
- git - 仅在选项卡中获取 git diff 输出