CREATE OR REPLACE VIEW ranked_files AS
SELECT
file.id,
file.untouched_basename,
DENSE_RANK() OVER (PARTITION BY movie.title, movie.year, file.feature_type_id, file.plex_title ORDER BY q.preference DESC) AS "rank"
FROM
file
JOIN movie
ON movie.id = file.movie_id
JOIN ref_quality q
ON q.id = file.quality_id
UNION
SELECT
file.id,
file.untouched_basename,
DENSE_RANK() OVER (PARTITION BY tv_series.id, file.season, file.episode ORDER BY q.preference DESC, file.last_episode DESC) AS "rank"
FROM
file
JOIN tv_series
ON tv_series.id = file.series_id
JOIN ref_quality q
ON q.id = file.quality_id;
View to make it easier to identify files by rank: