如何连接两个表,其中一些行部分留空?

How to join two tables with some lines being left partially blank?

从我原来的问题开始,这个问题对于一个问题来说太具体了: 我有 table 格式的匹配项:

ID|Player1|Player2|P1Score|P2Score
--+-------+-------+-------+-------
 1|     71|     83|      2|      0
 2|     73|     71|      1|      1
 3|     71|     65|      2|      0
 4|     65|     83|      0|      2

哪里

我需要得到一个 table 格式:

Player|Wins|Draws|Losses
------+----+-----+------
    71|   2|    1|     0
    73|   0|    1|     0
    83|   1|    0|     1
    65|   0|    0|     1

而且我不知道如何去做。

我最接近的是

SELECT Player1, COUNT(P1Score) FROM matches WHERE P1Score = 2 GROUP BY Player1

并重复平局和输球,然后加入 tables,对 P2 重复,并将值加在一起,但似乎 JOIN 不是我需要的命令.

2 is a win, 1 is a tie, and 0 is a loss

给定这些条件中的每一个,我们可以使用case表达式通过score计算相应的列。使用 union all 逆透视数据,然后 sum() 通过 Player:

聚合数据
select 
    Player
  , sum(Wins)   as Wins
  , sum(Draws)  as Draws
  , sum(Losses) as Losses
from (
  select 
      Player1 as Player
    , case when p1score = 2 then 1 else 0 end as Wins
    , case when p1score = 1 then 1 else 0 end as Draws
    , case when p1score = 0 then 1 else 0 end as Losses
  from t
  union all
  select 
      Player2 as Player
    , case when p2score = 2 then 1 else 0 end as Wins
    , case when p2score = 1 then 1 else 0 end as Draws
    , case when p2score = 0 then 1 else 0 end as Losses
  from t
  ) as s
group by Player

如果在比赛 table 中您使用 SCORE 而不是赢、输和平局的数字代码,这应该有效:

SELECT Player, SUM(WIN) AS WINS, SUM(DRAW) AS DRAWS, SUM(LOSS) AS LOSSES 
FROM ( 
 --Create a sub query where each row is how a player did in a given match
 SELECT A.Player, 
   (CASE WHEN (A.Player = B.Player1 AND B.P1Score>B.P2Score)
      OR (A.Player = B.Player2 AND B.P2Score>B.P1Score) THEN 1 ELSE 0 END) WIN,       
   (CASE WHEN (A.Player = B.Player1 AND B.P1Score<B.P2Score)
      OR (A.Player = B.Player2 AND B.P2Score<B.P1Score) THEN 1 ELSE 0 END) LOSS,
   (CASE WHEN B.P1Score=B.P2Score THEN 1 ELSE 0 END) DRAW
 FROM (
  SELECT DISTINCT Player
  FROM (
   SELECT Player1 FROM matches
   UNION ALL
   SELECT Player2 FROM matches
  ) A
 LEFT JOIN matches B
)