Ahoi大家
我非常 SQL新手,并为Uni做了一些功课。
我有以下两张表:
教授:
ID, Name
和 Assistans :
ID, Name, Boss (foreign key)
我的任务是找到拥有最多助手的教授。
到目前为止我所拥有的:
select top 1
p.name,
count (a.name) as NumberOfAssistants
from
Professors p, Assistants a
where
a.Boss = p.ID
group by
name
order by
NumberOfAssistants
我的问题是,有两位教授拥有相同和最大数量的助理。所以Top 1
对我不起作用。
我有点绝望,因为我无法绕过这个。希望你能帮帮我。
提前致谢
答案 0 :(得分:0)
也许你可以获得最大的数字并使用having
来获得你想要的东西。
尝试:
select p.name, count(a.name) as AmountOfAssistants from Professors p, Assistants a where a.Boss = p.ID group by name having AmountOfAssistants = (select count(a.name) as AmountOfAssistants from Professors p, Assistants a where a.Boss = p.ID group by name order by AmountOfAssistants desc limit 1);
答案 1 :(得分:0)
/*
create table Professors ( ID varchar(1), Name varchar(10) )
go
insert into Professors values ('1', 'Prof 1')
insert into Professors values ('2', 'Prof 2')
insert into Professors values ('3', 'Prof 3')
go
create table Assistants ( ID varchar(1), Name varchar(10), Boss varchar(1) )
go
insert into Assistants values ('1', 'Assist 1', '1')
insert into Assistants values ('2', 'Assist 2', '1')
insert into Assistants values ('3', 'Assist 1', '2')
insert into Assistants values ('4', 'Assist 1', '2')
insert into Assistants values ('5', 'Assist 1', '3')
go
*/
select p.ID, p.Name
from
Professors p
inner join Assistants a on p.ID = a.Boss
group by p.ID, p.Name
having
count(a.ID) =
(
select max(NumAssistants)
from (
select Boss, count(ID) as NumAssistants
from Assistants
group by Boss
) a
)