MySQL查询排除最高和最低计数

时间:2016-04-12 11:33:31

标签: mysql

我在MySql中有以下表格

Number
1
2
3
2
3
4
4
4

我想按计数获得数字,但排除最高和最低计数。这应该是结果

Number  Count
2       2
3       2

请帮我解决这个问题。

5 个答案:

答案 0 :(得分:2)

试试这个:

SELECT number, COUNT(*) cnt
FROM mytable
GROUP BY number
HAVING cnt <> (SELECT COUNT(*)
               FROM mytable
               GROUP BY number
               ORDER BY COUNT(*) LIMIT 1)
       AND               

       cnt <> (SELECT COUNT(*)
               FROM mytable
               GROUP BY number
               ORDER BY COUNT(*) DESC LIMIT 1)

HAVING子句中使用的两个子查询返回最小和最大计数。因此,HAVING子句的两个谓词过滤掉具有最高和最低计数的组。

答案 1 :(得分:1)

解决方案正在使用user variablesub-query

需要查询:

select Number, Count
from (
    select Number, count(*) as Count, @rank := @rank+1 as rank
    from t1 cross join (select @rank := 0) param
    group by Number
    order by Count ) t2 
where rank not in (1, @rank);

演示:

create table t1(Number int);
insert into t1 values(1),(2),(3),(2),(3),(4),(4),(4);

select Number, Count
from (
    select Number, count(*) as Count, @rank := @rank+1 as rank
    from t1 cross join (select @rank := 0) param
    group by Number
    order by Count ) t2 
where rank not in (1, @rank);

输出:

mysql> select Number, Count
    -> from (
    -> select Number, count(*) as Count, @rank := @rank+1 as rank
    -> from t1 cross join (select @rank := 0) param
    -> group by Number
    -> order by Count ) t2
    -> where rank not in (1, @rank);
+--------+-------+
| Number | Count |
+--------+-------+
|      2 |     2 |
|      3 |     2 |
+--------+-------+
2 rows in set (0.00 sec)

答案 2 :(得分:0)

select number,count(number)
from numbers 
where number not in ((select max(number) from numbers),(select min(number) from numbers)  )
group by number

sqlfiddle demo

答案 3 :(得分:0)

首先选择除最大和最小数字之外的所有行 然后从结果集中找到计数(数字)。

<强>查询

select t.number, count(t.number) as `Count` from(
    select * from your_table_name
    where number not in (
        select max(number) from your_table_name
    )
    and number not in (
        select min(number) from your_table_name
    )
)t
group by t.num;

答案 4 :(得分:-1)

SELECT列FROM tbl 限制10 OFFSET 20

SELECT MIN(taka)AS mintaka,MAX(taka)AS maxtaka FROM(SELECT taka FROM tbl LIMIT 10 OFFSET 20);