Search code examples
mysqlsqlinner-join

SQL Group by Count of Primary Key


I'm combining two tables with an inner join where the Primary ID is the movie ID, and I'd like to group them by number of movies per actor per year. However - possibly because the movie ID is the primary key - the results that I'm getting aren't correct. Below is my code. The DB is from iMDB, it has a cast table with movies and actors, an actors table and a movies table with the year.

SELECT 
                c.actor_id, m.year, COUNT(m.title)
            FROM
                cast c
            INNER JOIN movies m
            WHERE
                c.movie_id = m.id
            GROUP BY m.year
            ORDER BY COUNT(m.title) DESC;

Solution

  • Need to include actor_id in the GROUP clause cause you are counting number of movies per actor per year.

    SELECT 
                    c.actor_id, m.year, COUNT(m.title)
                FROM
                    cast c
                INNER JOIN movies m
                WHERE
                    c.movie_id = m.id
                GROUP BY c.actor_id, m.year
                ORDER BY COUNT(m.title) DESC;