Mysql前3个计数值

标签 mysql sql group-by count

我有一个返回以下值的查询:

TemplateCode    Total
    1418        35
    7419        31
    7418        31
    8325        17 
    15623       17
    4997        17

我想要包含前 3 个Total 值的所有行

在我的查询中,如果我在查询中包含LIMIT 3,那么它只给出我不想要的3。我不想包含 LIMIT,因为计数可能会不时变化。

如何在总计中包含条件并始终获得前 3 个计数值

我当前的查询如下:

select TemplateCode, count(*) as Total from table group by TemplateCode
order by Total desc
limit 3

最佳答案

我认为这符合你的要求:

select t.*
from t
where t.Total >= (select distinct t2.Total
                  from t t2
                  order by t2.Total desc
                  limit 2, 1
                 );

这假设您需要第三个不同值。如果您只需要第三个值,请删除 distinct

关于Mysql前3个计数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49328586/

相关文章:

php - 从数据库接收id不起作用,但我可以接收其他数据库字段

sql - 查询 SQL 字段是否包含多个值中的任意一个

sql - SQL Server中如何合并不同的行?

php - Android 使用 PHP 添加多个 MYSQL 行

php mysql_query 在插入后不返回任何内容(也没有插入任何内容)

php - Doctrine 2 : Cannot select entity through identification variables without choosing at least one root entity alias

php - 爆炸复选框循环php

sql - 具有两个参数的 PostgreSQL 中的间隔(天)

mysql - MySQL 中每个 id 的前 N ​​行

linux - Linux 中 .txt 文件的分组依据和求和