试图弄清楚如何找到最大数量

时间:2019-04-29 05:01:29

标签: mysql sql

  

名单中哪个团队成员最多?

好的,下面是我当前输入的代码。它返回所有团队以及每个团队有多少人。我不确定如何编写代码以仅显示成员最多的团队,因为当我尝试使用max函数和count函数时会出错。

SELECT Team_Name, COUNT(Member.Student_ID_Num) 
FROM Teams 
JOIN Member ON Teams.Team_Number = Member.Team_Number 
GROUP BY Team_Name

3 个答案:

答案 0 :(得分:3)

您可以尝试以下操作-按desc使用限制和顺序

Select Team_Name, count(Member.Student_ID_Num) as cnt
from Teams join Member on Teams.Team_Number = Member.Team_Number 
group by Team_Name
order by cnt desc
limit 1

答案 1 :(得分:2)

如果您使用的是MySQL 8+,则class A {} class A1 extends A{} class A2 extends A{} class AnyChildOfA extends A{} // want to achieve this but don't want to manually add the new derived or child class each time something changes type SubClassStrName = 'A1' | 'A2' | 'AnyChildOfA'; // This line is invalid syntax, but might tell what is desired type SubClassName<T> = <? extends T>.constructor.name; 函数在这里很方便:

ROW_NUMBER

如果您想让所有并列获得最高分,则应将两个或更多团队并列,然后将SELECT Team_Name, cnt FROM ( SELECT t.Team_Name, COUNT(*) AS cnt, ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) rn FROM Teams t INNER JOIN Member m ON t.Team_Number = m.Team_Number GROUP BY t.Team_Name ) t WHERE rn = 1; 替换为ROW_NUMBER

如果您必须以老式的方式执行此操作,而无需使用RANKLIMIT,则可以准备进行一个非常丑陋的查询:

ROW_NUMBER

答案 2 :(得分:0)

为了获得拥有最高会员人数的团队,我们不需要加入(除非我们也希望显示会员人数)。要记住的一件事是,可能有多个团队共享相同的最大成员数。

在没有任何限制子句(在标准SQL中为FETCH FIRST ROWS之前),标准SQL中的老式方式是:

  1. 每个团队人数计数成员。
  2. 获取最大数量。
  3. 获取具有此最大数量的团队编号。
  4. 获取这些团队编号的团队。

查询:

select *
from teams
where team_number in
(
  select team_number
  from member
  group by team_number
  having count(*) =
  (
    select max(cnt) as max_cnt
    from
    (
      select count(*) as cnt
      from member
      group by team_number
    ) counted
  )
);

从MySQL 8开始,我们宁愿使用wnindow函数,

select *
from teams
where (team_number, 1) in
(
  select team_number, rank() over (order by count(*) desc)
  from member
  group by team_number
);