MYSQL-latest results when grouping by a certain field
I have the following tables in my MYSQL database
Users table
id | login
---------------
1 | usuario1
2 | usuario2
3 | usuario3
Status table
id | idUsuario | data | status
1 | 1 | 2018-05-10 10:00:00 | a
2 | 2 | 2018-05-15 10:00:00 | a
3 | 3 | 2018-05-20 10:00:00 | a
4 | 3 | 2018-05-20 11:00:00 | d
5 | 1 | 2018-05-15 11:00:00 | d
6 | 3 | 2018-05-25 10:00:00 | a
How do I do a search in the STATUS table grouping by idUsuario
and showing only showing only the records where the status
with the latest data
equals a
This is the result I want to achieve with this query:
idUsuario | data | status
2 | 2018-05-15 10:00:00 | a
3 | 2018-05-25 10:00:00 | a
Any idea how I get to this result as efficiently as possible?
1
Author: Bruno Costa, 2018-06-07
1 answers
You can do like this:
SELECT idUsuario, MAX(data), status FROM STATUS
WHERE status = 'a'
GROUP BY idUsuario;
I hope I helped.
0
Author: Maycon F. Castro, 2018-06-07 20:07:07