2015-11-23 61 views
0

我有一個類似於下面的遊戲得分數據集。我試圖計算出使用類似的排名條件的新三列:在SQL中阻止CASE表達式,而不是跨行重複

數據集:

Player Player_Rank Score_Game1 Score_Game2 Score_Game3 
Tom  1 87 84 92 
John 2 91 84 87 
Peter 3 81 83 83 
Hank 4 85 72 57 
Alfred 5 60 58 54 
Mike 6 79 74 64 
Joe  7 49 81 62 
Marc 8 70 87 47 
Sean 9 73 51 69 

新列計算的Oracle SQL代碼:

case when Player_Rank <= 3 then Score_Game1 else . end as Score_Game1_r; 
case when Player_Rank <= 3 then Score_Game2 else . end as Score_Game2_r; 
case when Player_Rank <= 3 then Score_Game3 else . end as Score_Game3_r; 

有沒有辦法,我只是做一個案例聲明,像下面的東西,而不是重複它的所有列?

case when Player_Rank <= 3 then 
    Score_Game1 else . end as Score_Game1_r; 
    Score_Game2 else . end as Score_Game2_r; 
    Score_Game3 else . end as Score_Game3_r; 

最終數據將如下所示:

Player Player_Rank Score_Game1 Score_Game2 Score_Game3 Score_Game1_r Score_Game2_r Score_Game3_r 
Tom  1 87 84 92 87 84 92 
John 2 91 84 87 91 84 87 
Peter 3 81 83 83 81 83 83 
Hank 4 85 72 57 . . . 
Alfred 5 60 58 54 . . . 
Mike 6 79 74 64 . . . 
Joe  7 49 81 62 . . . 
Marc 8 70 87 47 . . . 
Sean 9 73 51 69 . . . 

我想有這樣的原因是,我要計算每個遊戲AVG(分數),也是AVG只爲玩家在任何時候都頂部3.謝謝。

+0

什麼SQL數據庫管理系統?基於實際的DBMS,可能的答案會有所不同。 – RBarryYoung

+0

Oracle。謝謝。 – user1839897

回答

1

您可以使用子查詢:

WITH data (Player, Player_Rank, Score_Game1, Score_Game2, Score_Game3) AS (
    SELECT 'Tom', 1, 87, 84, 92 FROM DUAL UNION ALL 
    SELECT 'John', 2, 91, 84, 87 FROM DUAL UNION ALL 
    SELECT 'Peter', 3, 81, 83, 83 FROM DUAL UNION ALL 
    SELECT 'Hank', 4, 85, 72, 57 FROM DUAL UNION ALL 
    SELECT 'Alfred', 5, 60, 58, 54 FROM DUAL UNION ALL 
    SELECT 'Mike', 6, 79, 74, 64 FROM DUAL UNION ALL 
    SELECT 'Joe', 7, 49, 81, 62 FROM DUAL UNION ALL 
    SELECT 'Marc', 8, 70, 87, 47 FROM DUAL UNION ALL 
    SELECT 'Sean', 9, 73, 51, 69 FROM DUAL 
) 
SELECT 
    player, 
    player_rank, 
    score_game1, 
    score_game2, 
    score_game3, 
    NVL(replace_by_dot, score_game1) score_game1_r, 
    NVL(replace_by_dot, score_game2) score_game2_r, 
    NVL(replace_by_dot, score_game3) score_game3_r 
FROM (
    SELECT 
     data.*, CASE WHEN Player_Rank > 3 THEN '.' ELSE NULL END replace_by_dot 
    FROM 
     data)