SQL ORDER BY子查询

时间:2015-02-08 13:58:55

标签: sql sql-server

我的查询是获取每个玩家的最高分以及该会话过去的时间。

在MySQL中使用以下查询并运行

SELECT Playername as 'Player Name', HighScores.P1Score as 'Highest Score', TimeElapsed as 'Elapsed Time'
FROM 
(gamerecord inner join playerprofile ON playerprofile.PID = gamerecord.PID),
(SELECT GID, PID, P1Score 
 FROM (SELECT GID, PID, P1Score 
       FROM gamerecord 
       ORDER BY 3 DESC) AS sortedtable 
 GROUP BY PID) AS HighScores 
WHERE gamerecord.GID = Highscores.GID

现在,使用MSSQL Server时,会引发以下错误。

ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOPOFFSETFOR XML

最里面的查询用于在GROUP BY操作之前首先对结果进行排序。据观察GROUP BY占据最高值,因此通过排序,我确保最高值是最高分。

如果没有抛出该错误,我怎样才能使用MSSQL?

1 个答案:

答案 0 :(得分:1)

我希望查询能够使用group查找每个游戏的最高得分,然后加入其余信息:

SELECT pp.Playername , gr.P1Score as HighestScore, gr.TimeElapsed 
FROM gamerecord gr inner join
     playerprofile pp
     ON pp.PID = gr.PID inner join
     (SELECT PID, max(p1score) as maxscore
      FROM gamerecord
      GROUP BY PID
     ) grmax
     ON gr.PID = grmax.PID and gr.p1score = grmax.maxscore;

order by不适合此类查询。