每组前3个值查询MS Access

时间:2016-07-02 01:48:50

标签: sql ms-access

我是MS访问的新手,我试图提出一个查询,以点数的形式提升3个不同类别中的前三名,即期望的结果是:

Child's name | Membership Type | Total Points
=============================================
Jon Snow     | Senior          | 12
Hodor        | Senior          | 13
Bran Stark   | Senior          | 67
Cersei       | Intermediate    | 14
Joffery      | Intermediate    | 19
Ramsay Bolton| Intermediate    | 25
Wun-Wun      | Junior          | 14
Arya Stark   | Junior          | 64
Ned Stark    | Junior          | 125

我已经找到了像这样的代码,我想/做了,

SELECT StudentID, TestID, TestScore
FROM MyTable t
WHERE TestID IN
(
SELECT TOP 3 TestID 
FROM MyTable
WHERE StudentID = t.StudentID 
ORDER BY TestScore DESC, TestID
)
ORDER BY StudentID, TestScore DESC, TestID;

但我不知道这意味着什么,更不用说如何调整它以满足我的需求。 有没有人知道如何获得所需的出局?

编辑:在版本中提交了一个语法错误。

SELECT [Members.Childs Name], [Members.Membership Type], [Results.Total Points]
FROM 
(SELECT [Members.Childs Name], [Members.Membership Type], [Results.Total Points],
        (SELECT Count(*) FROM [Results], [Members] sub
         WHERE sub.Total Points <= Results.Total Points
         AND sub.Membership Type = Members.Membership Type)  As GroupRank
FROM Members, Results t) As main
WHERE main.GroupRank <= 3
ORDER BY [main.Membership Type],[main.Total Points DESC]

P.S无关,但最后的结局令人惊讶:)

1 个答案:

答案 0 :(得分:2)

考虑一个计算顺序排名计数的相关子查询,然后您可以将其用作派生表来选择前三位:

SELECT main.StudentID, main.MembershipType, main.TestScore
FROM 
    (SELECT t.StudentID, t.MembershipType, t.TestScore,
            (SELECT Count(*) FROM MyTable sub 
             WHERE sub.TestScore >= t.TestScore
             AND sub.MembershipType = t.MembershipType) As GroupRank
     FROM MyTable t) As main
WHERE main.GroupRank <= 3
ORDER BY main.MembershipType, main.TestScore DESC

具体说明, GroupRank 是根据子查询(列中的嵌套选择)计算的,该子查询为外部查询的每个 MembershipType 排名 TestScores 。但是,这还不够,因为您需要使用此计算的 GroupRank 来选择前三名。因此,将整个查询嵌套在FROM子句中,该子句称为派生表,因为您创建了一个隐式表来返回另一个结果集。最终结果集筛选前三名,然后为每个成员订购 TestScores

在MS Access中,您可以将整个FROM子句查询保存为自己的存储查询,然后使用该查询过滤前三个:

SELECT g.StudentID, g.MembershipType, g.TestScore
FROM GroupRankQuery g    
WHERE g.GroupRank <= 3
ORDER BY g.MembershipType, g.TestScore DESC

对于多个表,使用表别名来帮助临时重命名表源以便于引用:

SELECT main.[Childs Name], main.[Membership Type], main.[Total Points] 
FROM 
   (SELECT m.[Childs Name], m.[Membership Type], r.[Total Points], 
           (SELECT Count(*) FROM [Results] subR 
            INNER JOIN [Members] subM ON subR.StudentID = subM.StudentID
            WHERE subR.[Total Points] >= r.[Total Points] 
            AND subM.[Membership Type] = m.[Membership Type]) As GroupRank 
    FROM Results r
    INNER JOIN Members m ON r.StudentID = m.StudentID) As main 
WHERE main.GroupRank <= 3 
ORDER BY main.[Membership Type], main.[Total Points] DESC