简体   繁体   中英

Mysql select max and sort date

'tbl'

| user | code | date |
| user 1 | 8549 | 2016-02-01 |
| user 2 | 7844 | 2016-02-17 |
| user 1 | 8675 | 2016-02-16 |
| user 3 | 2345 | 2016-02-21 |
| user 2 | 8545 | 2016-02-08 |

I have this set of records 'tbl' and i query to get the distinct user with it's latest date

SELECT user, code, max(date) as dt from tbl GROUP BY user

it returns:

| user | code | date |
| user 1 | 8675 | 2016-02-16 |
| user 2 | 7844 | 2016-02-17 |
| user 3 | 2345 | 2016-02-16 |

my problem is that i have no idea how to sort the date to desc. I want a result like this:

| user | code | date |
| user 1 | 8675 | 2016-02-16 |
| user 3 | 2345 | 2016-02-16 |
| user 2 | 7844 | 2016-02-17 |

Thanks :)

SELECT * 
FROM (
SELECT user, code, max(date) as dt from tbl GROUP BY user ) p
ORDER BY dt desc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM