我正在制作一个应用程序,可以显示人们对电影的评分,不论是热门还是热门。我想写一个查询来获取电影评分的次数。评级表如下所示:
| id | winner | loser |
| 1 | 1 | 2 |
| 2 | 2 | 3 |
| 3 | 1 | 3 |
通过运行这样的查询,我可以获得电影“赢了”的次数:
SELECT winner, count(winner) AS number_of_wins
FROM movie_results
GROUP BY winner
ORDER BY number_of_wins DESC;
但是我希望得到另一个查询,显示电影与其他电影相关的总次数,即电影似乎被评级的次数,是否被评为高于或低于另一部电影。仅使用SQL查询实现此目的的最简单方法是什么?
答案 0 :(得分:1)
以下是一种方法,使用becomes
:
union all
答案 1 :(得分:0)
您可以在两个派生表之间执行full join
,其中每个表包含每个玩家的损失和获胜次数。
select
coalesce(winner,loser) player,
coalesce(number_of_wins,0) number_of_wins,
coalesce(number_of_losses,0) number_of_losses,
coalesce(number_of_wins,0) + coalesce(number_of_losses,0) number_of_matches
from (
select winner, count(*) number_of_wins
from movie_results
group by winner
) winners full join (
select loser, count(*) number_of_losses
from movie_results
group by loser
) losers on losers.loser = winners.winner