我怎样才能在这里找到3个最常出现的同伴

时间:2016-11-07 14:34:17

标签: sql sql-server sql-server-2008 tsql

表1 - tblCompanion

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

我一直在尝试这几个小时,但无法得到如上所述的结果集, 请向我解释如何解决这个问题。

1 个答案:

答案 0 :(得分: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