2015-08-23 237 views
1

我正在製作一個應用程序,顯示人們對電影進行評分的評分。我想編寫一個查詢,獲取電影評分的次數。對評級表是這樣的:計算幾列中的出現次數

| 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查詢?

回答

1

這裏有一個方法,使用union all

select movie, count(*) as nummatches, sum(win) as numwins 
from ((select winner as movie, 1 as win from match_results) union all 
     (select loser, 0 from match_results) 
    ) wl 
group by movie; 
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 

http://sqlfiddle.com/#!15/980d6/3