查找列的最大值,按另一表中的列分组

时间:2020-05-06 09:00:55

标签: sql sql-server tsql join greatest-n-per-group

Schemea

我正在尝试为上述数据库/表编写一个查询,该查询将返回每位导演排名最高的电影。

我尝试过:

SELECT d.id, md.movie_id, m.name, m.year, MAX(m.rank)
FROM directors d
INNER JOIN movies_directors md
ON d.id = md.director_id
INNER JOIN movies m
ON md.movie_id = m.id
GROUP BY d.id

但它正在返回:

[Code: 8120, SQL State: S0001]  Column 'movies_directors.movie_id' is invalid in the select list 
because it is not contained in either an aggregate function or the GROUP BY clause.

1 个答案:

答案 0 :(得分:1)

这是每组排名前1的问题。除了聚合之外,您还需要某种过滤逻辑。

通常可以使用row_number()

select *
from (
    select 
        d.id, 
        md.movie_id, 
        m.name, 
        m.year, 
        row_number() over(partition by d.id order by m.rank desc) rn
    from directors d
    inner join movies_directors md on d.id = md.director_id
    inner join movies m on md.movie_id = m.id
) t
where rn = 1