简体   繁体   中英

(MySQL) Select row based off max count and tiebreaker logic

I have a query that currently pulls the count of a number for each user and the date the record was created.

user number num date_created
1 AA1 2 3/1/2022
1 BB1 2 4/1/2022
1 CC1 1 1/1/2020

I want the row with the highest count and most recent date as a tiebreaker, in my example, BB1. I'm having a hard time figuring out what steps to take next with my query:

SELECT id, number, count(dl.number) as 'num', date_created
FROM some_table
WHERE id = 1
GROUP BY id, number;

I have tried putting this into a subquery to alias, and use max() on count and date_created, but it does not get me what I'm looking for.

Very much appreciate any help. Thank you!

You can sort by the criteria you want in descending order using ORDER BY , and then pick the first one only using LIMIT :

select *
from some_table
where user = 1
order by num desc, date_created desc
limit 1

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