Frage

i want to select the actors with the most participations in movies

i know that with

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

it will show all the actors participating in a movie and it will count their participations But how can i show only the actor*/actors* with the most participations

i'm using SQL Server 2012

War es hilfreich?

Lösung

You can say something like this (untested);

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

or (a little simpler)

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

Or you can avoid partitioning the result set and ranking it by using something like this:

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

Andere Tipps

Most databases support window/analytic functions, including SQL Server 2012. The function max() is quite useful here:

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;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top