I have a movie table with over 100 different movies, shown below on PostgreSQL:
I want the name of each most-recent released movie, according to EACH GENRE.
How do I get the following output below on PostgreSQL:
2
You can use a window function such as DENSE_RANK() and filter by returning value equals to 1 like in the following one
DENSE_RANK()
SELECT Genre, Movie_Name FROM ( SELECT t.*, DENSE_RANK() OVER (PARTITION BY Genre ORDER BY Released_Date DESC) AS dr FROM t ) tt WHERE dr = 1
where
PARTITION BY
GROUP BY
DESC
ORDER
BY
ROW_NUMBER()
Use DISTINCT ON to get distinct genres. The ORDER BY will give you the most recent one for each genre.
DISTINCT ON
ORDER BY
SELECT DISTINCT ON (Genre) Movie_Name, Genre, Released_Date FROM movie_table m ORDER BY Genre, Released_Date DESC
Click here to cancel reply.
2
Answers
You can use a window function such as
DENSE_RANK()
and filter by returning value equals to 1 like in the following onewhere
PARTITION BY
meansGROUP BY
DESC
endinglyORDER
ingBY
means to get the latest onesDENSE_RANK()
function keeps ties of Released_Dates(equal datevalues per each group) unlike to
ROW_NUMBER()
Use
DISTINCT ON
to get distinct genres. TheORDER BY
will give you the most recent one for each genre.