我遇到了一个复杂的 SELECT 问题,所以我希望你们中的一些人可以帮助我,因为我真的很坚持......或者你可以给我指明一个方向。
我有一个包含以下列的表格:
score1, gamedate1, score2, gamedate2, score3, gamedate3
基本上我需要根据 ASCENDING 顺序的游戏时间来确定所有游戏的最终获胜者,谁首先获得了 SUMMED MAX 得分。
我遇到了一个复杂的 SELECT 问题,所以我希望你们中的一些人可以帮助我,因为我真的很坚持......或者你可以给我指明一个方向。
我有一个包含以下列的表格:
score1, gamedate1, score2, gamedate2, score3, gamedate3
基本上我需要根据 ASCENDING 顺序的游戏时间来确定所有游戏的最终获胜者,谁首先获得了 SUMMED MAX 得分。
假设 1,2,3 是不同的玩家,这样的事情应该可以工作:
-- construct table as the_lotus suggests
WITH LotusTable AS
(
SELECT 'P1' AS Player, t.Score1 AS Score, t.GameDate1 as GameDate
FROM Tbl t
UNION ALL
SELECT 'P2' AS Player, t.Score2 AS Score, t.GameDate2 as GameDate
FROM Tbl t
UNION ALL
SELECT 'P3' AS Player, t.Score3 AS Score, t.GameDate3 as GameDate
FROM Tbl t
)
-- get running scores up through date for each player
, RunningScores AS
(
SELECT b.Player, b.GameDate, SUM(a.Score) AS Score
FROM LotusTable a
INNER JOIN LotusTable b -- self join
ON a.Player = b.Player
AND a.GameDate <= b.GameDate -- a is earlier dates
GROUP BY b.Player, b.GameDate
)
-- get max score for any player
, MaxScore AS
(
SELECT MAX(r.Score) AS Score
FROM RunningScores r
)
-- get min date for the max score
, MinGameDate AS
(
SELECT MIN(r.GameDate) AS GameDate
FROM RunningsScores r
WHERE r.Score = (SELECT m.Score FROM MaxScore m)
)
-- get all players who got the max score on the min date
SELECT *
FROM RunningScores r
WHERE r.Score = (SELECT m.Score FROM MaxScore m)
AND r.GameDate = (SELECT d.GameDate FROM MinGameDate d)
;
有更有效的方法来做到这一点;特别是,可以避免自连接。
如果您的表设置了三列:player_id、score1、time
然后你只需要一个简单的查询来总结他们的分数并按 player_ID 分组,如下所示:
SELECT gamedata1.player_ID as 'Player_ID',
sum(gamedata1.score1 + gamedata2.score1 + gamedata3.score1) as 'Total_Score'
FROM gamedata1
LEFT JOIN gamedata2 ON (gamedata1.player_ID = gamedata2.player_ID)
LEFT JOIN gamedata3 ON (gamedata1.player_ID = gamedata3.player_ID)
GROUP BY 'player_ID'
ORDER BY time ASC
说明:您实际上是按每个玩家分组,因此您可以在每一行中获得一个不同的玩家,然后将他们的得分相加并以这种方式组织数据。我把“时间”作为日期类型。可以将粗略更改为您喜欢的任何日期类型等。查询的结构将是相同的。