SQL count by group

前端 未结 2 808
野趣味
野趣味 2021-01-26 14:00

I have to following schema

Movie(mvID, title, rating, year)
Director(directorID, firstname, lastname)
Genre(mvID*, genre)
Direct(mvID*, directorID*)
相关标签:
2条回答
  • 2021-01-26 14:46

    The SQL below will solve your problem:

    SELECT      Director.DirectorID, Director.FirstName, Director.LastName, COUNT(*)
    FROM        Direct, Genre, Director
    WHERE       Direct.mvID = Genre.mvID
    AND     Genre.genre = 'Comedy'
    AND     Direct.DirectorID = Director.DirectorID
    AND     rownum = 1
    GROUP BY    Director.DirectorID, Director.FirstName, Director.LastName
    order by    COUNT(*) DESC
    

    Specifically, this joins the tables and counts the movies directed by each director for movies of genre 'Comedy'. Then it sorts the row in descending order of count and grabs the first row.

    Note you have two many<->many relationships so if you weren't only looking at comedy (i.e. if you ran this across multiple genres), you would probably have to use a different technique (i.e. multiple temp tables or similar virtual aggregates) in order to not have 'double counting in your SQL...

    Also note that if two directors have the same count of movies for this genre, only one row would be brought back. You would have to modify the sql slightly if you wanted all directors with the same count of comedies to be returned.

    Cheers, Noah Wollowick

    0 讨论(0)
  • 2021-01-26 14:50
    select d.firstname,d.lastname,count(g.mvId)
    from Director d
    inner join Direct dr on d.directorId=dr.directorId
    inner join Genre g on dr.mvId=g.mvId
    where g.genre='comedy'
    group by d.firstname
    having count(g.mvId)=max(g.mvId)
    
    0 讨论(0)
提交回复
热议问题