Mysql 以下SQL查询的正确解决方案是什么?

Mysql 以下SQL查询的正确解决方案是什么?,mysql,sql,group-by,count,greatest-n-per-group,Mysql,Sql,Group By,Count,Greatest N Per Group,我已尝试以下查询,但出现错误: select ACTIVITY from (select ACTIVITY, count(*) as cnt, max(count(*)) as max_cnt, min(count(*)) as min_cnt from FRIENDS GROUP BY ACTIVITY) FRIENDS where cnt not in (max_cnt, min_cnt); 错误:第1行的错误1111 HY0

我已尝试以下查询,但出现错误:

select ACTIVITY
from (select ACTIVITY, count(*) as cnt,
             max(count(*)) as max_cnt,
             min(count(*)) as min_cnt
      from FRIENDS GROUP BY ACTIVITY) FRIENDS
where cnt not in (max_cnt, min_cnt);
错误:第1行的错误1111 HY000:组函数的使用无效 MYSQL版本:8


您需要窗口功能:

select ACTIVITY
from (select ACTIVITY, count(*) as cnt,
             max(count(*)) over () as max_cnt,
             min(count(*)) over () as min_cnt
      from FRIENDS 
      group by activity
     ) a
where cnt not in (max_cnt, min_cnt);
以上要求MySQL 8+。在早期版本中,更痛苦的是:

select a.ACTIVITY
from (select ACTIVITY, count(*) as cnt,
             max(count(*)) over () as max_cnt,
             min(count(*)) over () as min_cnt
      from FRIENDS 
      group by activity
     ) a join
     (select min(cnt) as min_cnt, max(cnt) as max_cnt
      from (select activity, count(*) as cnt
            from friends
            group by activity
           ) a
     ) am
     on a.cnt not in (am.max_cnt, am.min_cnt);

试试下面的方法,它应该可以在MySQL 8.0中使用窗口功能


假设您没有运行MySQL 8.0,否则前面问题的答案就可以了

在早期版本中,您可以执行以下操作:

select activity, count(*) no_activities
from friends
group by activity
having 
        count(*) > (select count(*) from friends group by activity order by count(*)  asc limit 1)
    and count(*) < (select count(*) from friends group by activity order by count(*) desc limit 1)

尽管如此,它还是在第3行出现了错误,在第1行出现了错误1064 42000:您的SQL语法中有一个错误;请查看与您的MySQL服务器版本对应的手册,以了解第3行的“as max_cnt,mincount*over as min_cnt from FRIENDS”附近使用的语法是否正确?除了MySQL中的窗口功能,还有其他方法吗?第14版?我严重过时了,这也是一个错误:第1行的错误1111 HY000:组的无效使用function@NirajSingh您使用的是哪个MySQL版本?我使用的是8@NirajSingh我添加了另一个使用窗口函数的解决方案,它也可以用来解决您的问题。
select activity, count(*) no_activities
from friends
group by activity
having 
        count(*) > (select count(*) from friends group by activity order by count(*)  asc limit 1)
    and count(*) < (select count(*) from friends group by activity order by count(*) desc limit 1)