按日期排序不同的列

时间:2013-05-27 20:58:29

标签: sql sql-order-by

我遇到一个复杂的SELECT问题,所以我希望你们中的一些人可以帮助我,因为我真的坚持了......或许你可以指出我的方向。

我有一个包含以下列的表:

score1, gamedate1, score2, gamedate2, score3, gamedate3

基本上我需要确定所有比赛的最终赢家,他们根据ASCENDING订单中的比赛时间获得SUMMED MAX得分第一。

2 个答案:

答案 0 :(得分:1)

假设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)
;

有更有效的方法;特别是,可以避免自我联接。

答案 1 :(得分:0)

如果你的表设置了三列:player_id,score1,time

然后你只需要一个简单的查询来总结他们的分数,并按照如下的方式将它们分组:

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

说明: 你基本上是由每个玩家分组,这样你就可以在每一行中获得一个独特的玩家,然后将他们的分数相加并以这种方式组织数据。我把“时间”作为日期类型。可以将粗略更改为您希望的任何日期类型等。查询的结构将是相同的。