Mysql - Sort before grouping

Asked

Viewed 668 times

0

I need to make a selection that brings the last users who logged in, without repeating the names. The problem is that the command below first groups and then sorts:

SELECT usuario FROM tab_logins GROUP BY usuario ORDER BY data_login  desc

Table example:

usuario, data_login
joão,    2018-01-01
maria,   2018-01-02
jose,    2018-01-03
joão,    2018-01-04
antonio, 2018-01-05
joão,    2018-01-06

Using the command I mentioned. First you will group the names, and then you will sort, bringing a wrong result:

antonio
jose
maria
joao

Since the correct result would be this:

joão
antonio
jose
maria

Does anyone know how to solve?

1 answer

0


There’s a way to fix it this way:

SELECT usuario
FROM tab_logins 
GROUP BY usuario 
ORDER BY MAX(data_login) desc;

The only difference is the application of the function MAX()

  • Perfect, @maxfratane! Worked perfectly. Thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.