无法对包含 MySql 中的聚合或子查询的表达式执行聚合函数

Posted

技术标签:

【中文标题】无法对包含 MySql 中的聚合或子查询的表达式执行聚合函数【英文标题】:Cannot perform an aggregate function on an expression containing an aggregate or a subquery in MySql 【发布时间】:2020-12-27 04:00:27 【问题描述】:

我想知道, 哪门课上的学生最多?

create table studies(
PNAME varchar(20),
INSTITUTE varchar(20),
COURSE varchar(20),
COURSEFEE int
);

insert into studies values
('Anand','Sabhari','PGDCA',4500),
('Altaf', 'Coit','DCA',7200),
('Juliana', 'Bdps','MCA',2200),
('Kamala', 'Pragathi','DCA',5000),
('Mary', 'Sabhari','PGDCA',4500),
('Nelson', 'Pragathi','DAP',6200),
('Patrick', 'Pragathi','DCAP',5200),
('Qadir', 'Apple','HDCA',1400),
('Ramesh', 'Sabhari','PGDCA',4500),
('Rebecca', 'Brilliant','DCAP',11000),
('Remitha', 'Bdps','DCS',6000),
('Revathi', 'Sabhari','DAP',5000),
('Vijaya', 'Bdps','DCA',4800);

查询尝试:

SELECT COURSE
FROM STUDIES
GROUP BY COURSE
HAVING COUNT(COURSE)= (SELECT MAX(COUNT(COURSE))
FROM STUDIES
GROUP BY COURSE)

【问题讨论】:

错误信息似乎不言自明 【参考方案1】:

如果你真的想让你当前的版本工作,HAVING 子句中的子查询需要更多的工作:

SELECT COURSE, COUNT(*) AS cnt
FROM STUDIES
GROUP BY COURSE
HAVING COUNT(*) = (SELECT MAX(cnt)
                   FROM (SELECT COUNT(*) AS cnt
                         FROM STUDIES
                         GROUP BY COURSE) t);

假设您希望课程数量最多,并且您不希望重复,您可以在这里使用LIMIT 查询:

SELECT COURSE, COUNT(*) AS cnt
FROM STUDIES
GROUP BY COURSE
ORDER BY COUNT(*) DESC
LIMIT 1;

或者,如果您的 mysql 版本是 8 或更高版本,您可以在此处使用 RANKROW_NUMBER

WITH cte AS (
    SELECT COURSE, COUNT(*) AS cnt,
           RANK() OVER (ORDER BY COUNT(*) DESC) rnk
    FROM STUDIES
    GROUP BY COURSE
)

SELECT COURSE, cnt
FROM cte
WHERE rnk = 1;

【讨论】:

HAVING 子句可以简化为:HAVING COUNT(*) = (SELECT COUNT(*) FROM STUDIES GROUP BY COURSE ORDER BY COUNT(*) DESC LIMIT 1)【参考方案2】:

你可以单独使用一个:

SELECT COURSE FROM `STUDIES` HAVING COUNT(COURSE)

如果你想要多个:

SELECT COURSE
FROM STUDIES
GROUP BY COURSE
HAVING COUNT(*) = (SELECT MAX(subject)
                  FROM (SELECT COUNT(*) AS subject
                    FROM STUDIES
                    GROUP BY COURSE) rs
                  )

【讨论】:

以上是关于无法对包含 MySql 中的聚合或子查询的表达式执行聚合函数的主要内容,如果未能解决你的问题,请参考以下文章

对计算的 SUM 值执行 AVG

没有聚合或子查询的查询

聚合和连接 2 个表或子查询

在聚合表达式中使用包含时 sql 查询出错

NHibernate 查询:包含在父属性或子属性中的字符串

SQL Server 索引视图:无法创建聚集索引,因为选择列表包含聚合函数结果的表达式