以下 SQL 查询的正确解决方案是什么?
What is the correct solution for the below SQL query?
我尝试了以下查询,但出现错误:
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);
ERROR: ERROR 1111 (HY000) at line 1: Invalid use of group function
MYSQL VERSION: 8
您需要 window 个功能:
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
中的 window 函数。
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
据推测,你不是 运行 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)
我尝试了以下查询,但出现错误:
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);
ERROR: ERROR 1111 (HY000) at line 1: Invalid use of group function MYSQL VERSION: 8
您需要 window 个功能:
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
中的 window 函数。
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
据推测,你不是 运行 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)