我有一个MYSQL表,看起来像:
+----+--------------+------------+----------------+---------------------+
| id | id_solicitud | id_estatus | id_responsable | fecha_hora |
+----+--------------+------------+----------------+---------------------+
| 1 | 1 | 1 | 3 | 2017-11-20 11:12:05 |
| 3 | 1 | 2 | 3 | 2017-11-20 13:30:50 |
| 4 | 2 | 1 | 5 | 2017-11-20 13:42:35 |
| 5 | 2 | 2 | 5 | 2017-11-20 13:52:25 |
| 6 | 1 | 4 | 2 | 2017-11-21 12:20:17 |
| 8 | 2 | 3 | 2 | 2017-11-21 13:39:57 |
| 9 | 2 | 2 | 5 | 2017-11-21 13:40:55 |
| 10 | 2 | 4 | 2 | 2017-11-21 13:45:24 |
+----+--------------+------------+----------------+---------------------+
然后,我继续使用以下Mysql QUERY过滤 id_solicitud 字段:
SELECT id_estatus,id_responsable,fecha_hora FROM estatus_historico WHERE id_solicitud = 2 ORDER BY fecha_hora
结果:
+------------+----------------+---------------------+
| id_estatus | id_responsable | fecha_hora |
+------------+----------------+---------------------+
| 1 | 5 | 2017-11-20 13:42:35 |
| 2 | 5 | 2017-11-20 13:52:25 |
| 3 | 2 | 2017-11-21 13:39:57 |
| 2 | 5 | 2017-11-21 13:40:55 |
| 4 | 2 | 2017-11-21 13:45:24 |
+------------+----------------+---------------------+
我想在 id_estatus 列上应用distinct运算符,但在找到重复行时选择较旧的行,即我想要的结果是:
+------------+----------------+---------------------+
| id_estatus | id_responsable | fecha_hora |
+------------+----------------+---------------------+
| 1 | 5 | 2017-11-20 13:42:35 |
| 3 | 2 | 2017-11-21 13:39:57 |
| 2 | 5 | 2017-11-21 13:40:55 |
| 4 | 2 | 2017-11-21 13:45:24 |
+------------+----------------+---------------------+
我试过了:
SELECT id_estatus,id_responsable,fecha_hora FROM estatus_historico WHERE id_solicitud = 2 GROUP BY id_estatus ORDER BY fecha_hora
但结果是错误的:
+------------+----------------+---------------------+
| id_estatus | id_responsable | fecha_hora |
+------------+----------------+---------------------+
| 1 | 5 | 2017-11-20 13:42:35 |
| 2 | 5 | 2017-11-20 13:52:25 |
| 3 | 2 | 2017-11-21 13:39:57 |
| 4 | 2 | 2017-11-21 13:45:24 |
+------------+----------------+---------------------+
非常感谢任何帮助
更新:要创建表格和插入数据的文件=> estatus_historico.sql
答案 0 :(得分:0)
尝试这个
SELECT id_estatus, id_responsable, MAX(fecha_hora) FROM estatus_historico WHERE id_solicitud =2 GROUP BY id_estatus ORDER BY fecha_hora
答案 1 :(得分:0)
感谢Rahul Shrivastava,我终于找到了正确答案:
SELECT * FROM (
SELECT id_estatus, id_responsable, MAX( fecha_hora ) AS fecha
FROM estatus_historico
WHERE id_solicitud =2
GROUP BY id_estatus
ORDER BY fecha_hora
) AS MY_TABLE ORDER BY fecha