2016-11-07 33 views
1

表1 - tblCompanion我怎樣才能得到這裏的3個最頻繁出現的同伴

companionid | companionname | who played 
--------------------------------------------------- 
1   | River Song  | Alex Kingston 
2   | Rory Williams | Arthur Darvill 
3   | Wilfred Mott  | Bernard Cribbins 
4   | Rose Tyler  | Billie Piper 
5   | Adam Mitchell | Bruno Langley 
6   | Donna Noble  | Catherine Tate 
7   | Jackson Lake  | David Morrissey 
8   | Sarah Jane Smith | Elisabeth Sladen 
.   | .    | . 
.   | .    | . 
.   | .    | . 

表2 - tblEpisodeCompanion

Episodecompanionid | EpisodeId | companionid 
--------------------------------------------- 
1     | 1   | 4 
2     | 2   | 4 
3     | 3   | 4 
4     | 4   | 4 
5     | 5   | 4 
6     | 6   | 4 
7     | 7   | 4 
8     | 8   | 6 
9     | 9   | 6 
10     | 10  | 6 
11     | 11  | 1 
12     | 12  | 1 
13     | 13  | 2 
.     | .   | . 
.     | .   | . 
.     | .   | . 

從這兩個表我想這些結果:

No | companianName | Episodes 
----------------------------- 
1 | Amy Pond  | 33 
2 | Rose Tyler | 32 
3 | Rory Williams | 25 

我一直在嘗試這個小時,但不能得到如上所述的結果集, 請向我解釋如何解決這個問題。

+3

你嘗試過什麼?這看起來像一個非常基本的'JOIN'和'GROUP BY'查詢。 –

回答

0

這個查詢應該爲你做的:

SELECT TOP 3 
    tblCompanion.companionname, 
    Count(*) AS Episodes 
FROM tblEpisodeCompanion 
    INNER JOIN tblCompanion 
     ON tblEpisodeCompanion.companionid = tblCompanion.companionid 
GROUP BY tblCompanion.companionname 
ORDER BY Count(*) DESC