mysql:为什么这两个错误(组函数使用无效,使用having()后未选择任何内容)

ovfsdjhp  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(500)

credit:leetcode_1076.project 员工二这是项目表的样本表:

project_id  | employee_id 

 1           | 1           
 1           | 2           
 1           | 3           
 2           | 1           
 2           | 4

(project\u id,employee\u id)是此表的主键。
我尝试了几种方法,并通过使用dense_rank()找到了正确的方法;然而,我仍然不明白为什么这两个语法选择员工人数最多的项目id是错误的:
1.return null:{“headers”:[“project\u id”,“n”],“values”:[]}

select project_id, count(*) as n
from project
group by project_id
having max(n)

我希望它返回{“headers”:[“project\u id”,“n”],“values”:[1,3]}。
2.错误:组函数的使用无效

SELECT project_id, max(count(*)) as n
from project 
group by project_id

如果有人能帮我,我真的很感激!!

zsbz8rwp

zsbz8rwp1#

这两种方法都有一个共同的问题,即您试图在同一级别访问sql中的聚合结果。sql中不能有嵌套的聚合函数(例如max(count(1))。
您的sql应该如下-

select t.project_id, max(t.n) from (select project_id, count(*) as n
from project
group by project_id) t;

sqlfiddle演示-http://sqlfiddle.com/#!9/9c9b18/4号

q43xntqr

q43xntqr2#

使用 order by 以及 limit :

select project_id, count(*) as n
from project
group by project_id
order by n desc
limit 1;

如果要处理领带,请使用窗口函数:

select p.*
from (select project_id, count(*) as n,
             rank() over (order by count(*) desc) as seqnum
      from project
      group by project_id
     ) p
where seqnum = 1;

相关问题