Can I do a max(count(*)) in SQL?

前端 未结 11 1833
遥遥无期
遥遥无期 2020-11-29 01:02

Here\'s my code:

    select yr,count(*)  from movie
join casting on casting.movieid=movie.id
join actor on casting.actorid = actor.id
where actor.name = \'Jo         


        
11条回答
  •  一个人的身影
    2020-11-29 01:54

    Using max with a limit will only give you the first row, but if there are two or more rows with the same number of maximum movies, then you are going to miss some data. Below is a way to do it if you have the rank() function available.

    SELECT
        total_final.yr,
        total_final.num_movies
        FROM
        ( SELECT 
            total.yr, 
            total.num_movies, 
            RANK() OVER (ORDER BY num_movies desc) rnk
            FROM (
                   SELECT 
                          m.yr, 
                          COUNT(*) AS num_movies
                   FROM MOVIE m
                   JOIN CASTING c ON c.movieid = m.id
                   JOIN ACTOR a ON a.id = c.actorid
                   WHERE a.name = 'John Travolta'
                   GROUP BY m.yr
                 ) AS total
        ) AS total_final 
       WHERE rnk = 1
    

提交回复
热议问题