使用条件从diff列聚合总和。 PL / SQL

时间:2015-12-16 15:33:42

标签: plsql

任务是了解玩家在一年中赚了多少钱。 所以我想写一个选择,在已知player_id的情况下,我将汇总他的总胜利。

tournament scheme

FIRST_PLAYER_ID是相应的第一名和FIRST_PRICE的玩家ID。

我需要什么:

player_id | total_prize_sum_over_all_tournaments_played_by_him

我到目前为止尝试的代码:

SELECT PLAYER.SUNAME, TOURNAMENT.NAME FROM PLAYER
JOIN TOURNAMENT
ON PLAYER.ID = TOURNAMENT.FIRST_PLAYER_ID
OR PLAYER.ID = TOURNAMENT.SECOND_PLAYER_ID
OR PLAYER.ID = TOURNAMENT.THIRD_PLAYER_ID
ORDER BY PLAYER.BIRTH_DATE

另外,请帮我正确命名这个问题。

1 个答案:

答案 0 :(得分:1)

以下sql语句汇总每位玩家赢得的奖金。这个想法是分别按每个等级进行汇总,然后总结每个玩家的结果。

    SELECT pt.p_id
         , SUM(pt.tl)
      FROM (
                SELECT p.p_id
                     , sum(t.first_prize)   tl
                  FROM player p
                  JOIN tournament t on ( t.first_player_id    = p.p_id )
              GROUP BY p.p_id
             UNION ALL
                SELECT p.p_id
                     , sum(t.second_prize)  tl
                  FROM player p
                  JOIN tournament t on ( t.second_player_id    = p.p_id )
              GROUP BY p.p_id
             UNION ALL
                SELECT p.p_id
                     , sum(t.third_prize)   tl
                  FROM player p
                  JOIN tournament t on ( t.third_player_id    = p.p_id )
              GROUP BY p.p_id
            ) pt      
   GROUP BY pt.p_id
          ;

This sql fiddle是一个成熟的例子(限制表定义)。