2013-05-27 79 views
0

我遇到了一個複雜的SELECT問題,所以我希望你們中的一些人可以幫助我,因爲我真的被困住了......或者你可以指點我一個方向。按日期排列不同列

我有一個表有以下欄目:

score1, gamedate1, score2, gamedate2, score3, gamedate3 

基本上,我需要確定所有的遊戲,誰得到了總結MAX得分第一的基礎上,按升序排列遊戲時代最後的贏家。

+2

如果可能的話,你應該改爲「分數,遊戲日期,號碼」,這將會更容易做查詢。 –

+1

任何你遇到麻煩的事情? [你有沒有試過我們可以查看的查詢?](http://whathaveyoutried.com) – Dukeling

+0

@the_lotus:嗨,thx的提示!,下次會嘗試你的方法! – Platanus79

回答

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

有這樣做的更有效的方法;特別是可以避免自聯接。

+0

親愛的馬克! Thx幫助您擺脫這種困境!我會嘗試你的解決方案! – Platanus79

+0

我喜歡這個名字;) –

0

如果你的表設置三列:player_id,score1,時間

然後你只需要一個簡單的查詢,通過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 

說明: 你基本上是由每個玩家組成的,所以你可以在每一行中得到一個獨特的玩家,然後總結他們的分數並以這種方式組織數據。我把「時間」作爲日期類型。可以更改粗糙到任何你想要的日期類型等。查詢的結構將是相同的。

+0

你近了......再次閱讀這個問題 - 他想要這筆款項改變順序 – Hogan