简体   繁体   English

(MySQL) Select 基于最大计数和决胜逻辑的行

[英](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 1个 AA1 AA1 2 2个 3/1/2022 2022 年 3 月 1 日
1 1个 BB1 BB1 2 2个 4/1/2022 2022 年 4 月 1 日
1 1个 CC1 CC1 1 1个 1/1/2020 2020 年 1 月 1 日

I want the row with the highest count and most recent date as a tiebreaker, in my example, BB1.我希望计数最高且日期最近的行作为决胜局,在我的示例中为 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.我已经尝试将其放入别名的子查询中,并在 count 和 date_created 上使用 max(),但它并没有让我得到我正在寻找的东西。

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 :您可以使用ORDER BY按降序排列所需的条件,然后仅使用LIMIT选择第一个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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