【问题标题】:What is the correct solution for the below SQL query?以下 SQL 查询的正确解决方案是什么?
【发布时间】:2020-08-07 08:40:13
【问题描述】:

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

ERROR: ERROR 1111 (HY000) at line 1: 无效使用组函数 MYSQL 版本:8

【问题讨论】:

  • 版本 14?我严重过时了

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


【解决方案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)

【讨论】:

    【解决方案2】:

    尝试以下,它应该可以使用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  
    

    【讨论】:

    • 这也给出了错误:ERROR 1111 (HY000) at line 1: Invalid use of group function
    • @NirajSingh 你用的是哪个MySQL 版本?
    • 我使用的是版本 8
    • @NirajSingh 我添加了另一个使用窗口函数的解决方案,也可以用来解决您的问题。
    【解决方案3】:

    你想要窗口函数:

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

    【讨论】:

    • 仍然在第 3 行出错 ERROR 1064 (42000) 在第 1 行:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 3 行使用 '() as max_cnt, min(count(*)) over () as min_cnt from FRIENDS' 附近的正确语法
    • 除了mysql中的窗口函数还有其他方法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多