我想选择电影参与度最高的演员
我知道
SELECT name,COUNT(name) AS counter
FROM actors a
INNER JOIN movies_actors ma ON a.a_id = ma.a_id
INNER JOIN movies m ON m.m_id = ma.m_id
GROUP BY name
ORDER BY counter DESC
它将显示参与电影的所有演员,并将计算他们的参与 但是我怎样才能只展示参与度最高的演员* / actors *
我正在使用SQL Server 2012
答案 0 :(得分:1)
你可以这样说(未经测试);
with actors ( name , counter , rank )
as
( SELECT name = a.name ,
counter = COUNT(*) ,
rank = rank() over ( order by count(*) desc )
FROM actors a
JOIN movies_actors ma ON a.a_id = ma.a_id
JOIN movies m ON m.m_id = ma.m_id
GROUP BY name
)
select *
from actors
where rank = 1
或(稍微简单一些)
select *
from ( SELECT name = a.name ,
counter = COUNT(*) ,
rank = rank() over ( order by count(*) desc )
FROM actors a
JOIN movies_actors ma ON a.a_id = ma.a_id
JOIN movies m ON m.m_id = ma.m_id
GROUP BY name
) t
where t.rank = 1
或者您可以避免对结果集进行分区并使用以下内容对其进行排名:
select t.movies , a.*
from ( select actor_id = a_id ,
movies = count(*)
from movies_actors
group by a_id
) t
join ( select max_movie = max( t.movie_count )
from ( select actor_id = a_id ,
movie_count = count(*)
from movies_actors
group by a_id
) t
) x on x.max_movies = t.movies
join actors a on a.id = t.a_id
答案 1 :(得分:0)
大多数数据库都支持窗口/分析功能,包括SQL Server 2012.函数max()
在这里非常有用:
SELECT name, counter
FROM (SELECT name, COUNT(*) AS counter, MAX(COUNT(*)) OVER () as maxcounter
FROM actors a INNER JOIN
movies_actors ma
ON a.a_id = ma.a_id INNER JOIN
movies m
ON m.m_id = ma.m_id
GROUP BY name
) n
WHERE counter = maxcounter;