Home > OS >  Window Function - DENSE_RANK
Window Function - DENSE_RANK

Time:09-19

My requirement is - "In which year most films were released?". The following query works fine

SELECT release_year, count(film_id)
from film
GROUP BY release_year 
ORDER BY count(film_id) DESC
LIMIT 1;

RESULT:

       -------------- ---------------- 
      | release_year | count(film_id) |
       -------------- ---------------- 
      |         2017 |            110 |
       -------------- ---------------- 

But the problem with this query is if same no. of movies were released during year 2016 also (suppose), I will not get that unless i mention Limit 2 (again i may not know limit value). So I tried it using DENSE_RANK() window function but I am unable to do so.

Please suggest how dense_rank() query would be?

CodePudding user response:

WITH
cte AS (
    SELECT release_year, 
           COUNT(film_id) cnt, 
           DENSE_RANK() OVER (ORDER BY COUNT(film_id) DESC) drnk
    FROM film
    GROUP BY release_year 
)
SELECT release_year, cnt
FROM cte
WHERE drnk = 1;
  • Related