SQLite - 获得每个游戏的胜利者(排名超过分区)

时间:2015-08-10 19:58:06

标签: sqlite greatest-n-per-group rank partition

我正在为卡尔卡松创建一个分数跟踪应用。我想获得每场比赛的冠军。

我已经在MS-SQL中工作了,现在我正在尝试将db转换为SQLite。

模式
http://sqlfiddle.com/#!7/e8340

MS-SQL

CREATE VIEW vTopScorePerGame AS
WITH ranked AS (
    SELECT      RANK() OVER (PARTITION BY [GameID] ORDER BY TotalScore DESC) AS Position,
                   PlayerID,
                PlayerName, 
                TotalScore,
                [GameID]
    FROM        vScore
)
SELECT      [GameID],
            PlayerID,
            PlayerName AS Winner,
            TotalScore
FROM        ranked      
WHERE       ranked.Position = 1

当我在SQLFiddle或SQLiteBrowser中尝试时,我收到以下错误:

near "(": syntax error:

有人能指出我正确的方向吗?

功能

https://www.sqlite.org/lang_with.html
COALESCE
https://www.sqlite.org/lang_corefunc.html

不支持的
http://www2.sqlite.org/cvstrac/wiki?p=UnsupportedSqlAnalyticalFunctions

1 个答案:

答案 0 :(得分:5)

如果你有SQLite 3.7.11或更高版本,你可以简单地使用MAX()从组中具有最大值的行中获取值:

SELECT GameID,
       PlayerID,
       PlayerName AS Winner,
       MAX(TotalScore) AS TotalScore
FROM vScore
GROUP BY GameID;

在早期版本中,您可以在单独的子查询中获得具有大分数的玩家,然后将其与原始表连接:

SELECT GameID,
       PlayerID,
       PlayerName AS Winner,
       TotalScore
FROM vScore
JOIN (SELECT GameID,
             (SELECT PlayerID
              FROM vScore AS s2
              WHERE s2.GameID = GameIDs.GameID
              ORDER BY TotalScore DESC
              LIMIT 1
             ) AS PlayerID
      FROM (SELECT DISTINCT GameID
            FROM vScore) AS GameIDs)
     USING (GameID, PlayerID);