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

时间:2020-04-23 21:14:19

标签: mysql sql group-by count greatest-n-per-group

Print name of all activities with neither maximum nor minimum number of participants

我尝试了以下查询,但给我错误:

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

3 个答案:

答案 0 :(得分:1)

大概您没有运行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)

答案 1 :(得分:0)

您想要窗口功能:

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);

答案 2 :(得分:0)

尝试以下操作,它应该使用MySQL 8.0中的窗口功能。

select
    activity
from
(
    select 
        activity, 
        count(*) over () as ttl,
        dense_rank() over (order by count(*)) as rnk
    from friends 
    group by 
        activity
)  val
where rnk != 1 and rnk != ttl - 1