mysql count group by having

后端 未结 4 1706
余生分开走
余生分开走 2020-12-02 22:10

I have this table:

Movies (ID, Genre)

A movie can have multiple genres, so an ID is not specific to a genre, it is a many to many relations

相关标签:
4条回答
  • 2020-12-02 22:40
    SELECT COUNT(*) 
    FROM   (SELECT COUNT(*) 
            FROM   movies 
            GROUP  BY id 
            HAVING COUNT(genre) = 4) t
    
    0 讨论(0)
  • 2020-12-02 22:56

    Maybe

    SELECT count(*) FROM (
        SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
    ) AS the_count_total
    

    although that would not be the sum of all the movies, just how many have 4 genre's.

    So maybe you want

    SELECT sum(
        SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
    ) as the_sum_total
    
    0 讨论(0)
  • 2020-12-02 22:58

    One way would be to use a nested query:

    SELECT count(*)
    FROM (
       SELECT COUNT(Genre) AS count
       FROM movies
       GROUP BY ID
       HAVING (count = 4)
    ) AS x
    

    The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.

    0 讨论(0)
  • 2020-12-02 23:02

    What about:

    SELECT COUNT(*) FROM (SELECT ID FROM Movies GROUP BY ID HAVING COUNT(Genre)=4) a
    
    0 讨论(0)
提交回复
热议问题