我有一张桌子(film_actor),它拥有另外两张桌子,电影和演员之间的关系。
我想在表film_actor中计算actor.id的出现次数,然后选择最高值或值,但似乎无法使其工作。
我的查询到目前为止如下所示,它给了我一个很好的所有演员列表和他们所在的电影数量。我似乎无法做的是选择最高值或值。我知道我可以将结果限制为1或前1,但我需要它是动态的,以防列表有2个或更多具有相同数量电影的演员。
SELECT actor.first_name, actor.last_name, COUNT(actor.actor_id) AS film_number
FROM actor
INNER JOIN film_actor ON actor.actor_id = film_actor.actor_id
GROUP BY actor.actor_id, actor.first_name, actor.last_name
ORDER BY film_number DESC
我还没有能够将MAX()嵌入其中,但我认为这就是我需要的。欢迎所有提示!
答案 0 :(得分:0)
编写此类查询的最佳方法是使用rank()
或dense_rank()
:
SELECT fa.*
FROM (SELECT a.first_name, a.last_name, COUNT(a.actor_id) AS film_number,
RANK() OVER (ORDER BY COUNT(a.actor_id) DESC) as seqnum
FROM actor a INNER JOIN
film_actor fa
ON a.actor_id = fa.actor_id
GROUP BY a.actor_id, a.first_name, a.last_name
) fa
WHERE seqnum = 1;
答案 1 :(得分:0)
我最终通过使用HAVING和ALL来解决这个问题,见下文:
SELECT
actor.first_name, actor.last_name, COUNT(film_actor.actor_id) as Antalfilmer
FROM
film_actor
INNER JOIN actor ON film_actor.actor_id = actor.actor_id
GROUP BY actor.first_name, actor.last_name, actor.actor_id
HAVING COUNT(film_actor.actor_id) >= ALL (SELECT COUNT(film_actor.actor_id) FROM film_actor JOIN actor ON actor.actor_id = film_actor.actor_id GROUP BY actor.first_name, actor.last_name, actor.actor_id)