SQL Server查询根据游戏结果返回排名

时间:2010-10-28 02:13:38

标签: sql sql-server tsql

我已经看过StackOverflow上同样问过的其他多个问题,但似乎没有什么能适合我的账单。我的查询稍微复杂一些。基本上,我需要找到条目的等级。

我的表结构是:

的TestEntry

Id, TotalTime, DateCreated

GameResult

GameId, TestEntryId, Duration, Score

QuestionResult

QuestionId, TestEntryId, Correct, UsersAnswer

计算所有分数的查询通过以下方式完成:

CREATE TABLE #GRS
(
TestEntryId uniqueidentifier,
Score int
)

CREATE TABLE #QRS
(
    TestEntryId uniqueidentifier,
    CorrectAnswers int
)
/* Populate temp tables with Game/Question results */
INSERT INTO #GRS
SELECT 
        TestEntryId, 
        SUM(Score) AS Score 
    FROM GameResult
    GROUP BY TestEntryId

INSERT INTO #QRS
SELECT 
        TestEntryId, 
        COUNT(*) CorrectAnswers
    FROM QuestionResult
    WHERE Correct = 1
    GROUP BY TestEntryId

SELECT 
        Id, ISNULL(GRS.Score,0) + (ISNULL(QRS.CorrectAnswers,0) * 25) AS Score
    FROM TestEntry TE
    LEFT JOIN #GRS GRS ON(GRS.TestEntryId = TE.Id)
    LEFT JOIN #QRS QRS ON(QRS.TestEntryId = TE.Id)
    WHERE TE.TotalTime > 0

基于特定的TestEntry.Id,我需要确定该条目的排名。由于临时表的使用证明是棘手的,并且TestEntry表中没有“TotalScore”,因此它是动态计算的。

1 个答案:

答案 0 :(得分:2)

除非迫切需要临时表,否则将它们解雇并使用公共表表达式。然后使用RANK函数获取每个id的排名。

;WITH GRS AS
(
    SELECT 
        TestEntryId, 
        SUM(Score) AS Score 
    FROM GameResult
    GROUP BY TestEntryId
),
QRS AS
(
SELECT 
        TestEntryId, 
        COUNT(*) CorrectAnswers
    FROM QuestionResult
    WHERE Correct = 1
    GROUP BY TestEntryId
),
Scores AS
(
SELECT 
        Id, ISNULL(GRS.Score,0) + (ISNULL(QRS.CorrectAnswers,0) * 25) AS Score
    FROM TestEntry TE
    LEFT JOIN GRS ON(GRS.TestEntryId = TE.Id)
    LEFT JOIN QRS ON(QRS.TestEntryId = TE.Id)
    WHERE TE.TotalTime > 0
)
SELECT Id,Score,RANK() OVER (ORDER BY Score DESC) AS [Rank] FROM Scores