MYSQL UNION和/或PIVOT

时间:2017-06-16 10:58:53

标签: mysql union

我已经提出了这个返回我需要的数据的查询 - 我被建议使用UNION并且可能是一个PIVOT但是SQL技能有限这就是我想出来的......我确实尝试了一个PIVOT但是得到了相同的结果

SELECT RoundNo, Team, WL
FROM `MatchDetails2017` 
WHERE Season = 2017 AND Team = 'Team A'
UNION
SELECT RoundNo, Team, WL
FROM `MatchDetails2017` 
WHERE Season = 2017 AND Team = 'Team B'

数据就像这样出现

RoundNo | Team  |WL  
R1 | Team A | W
R2 | Team A | L
R3 | Team A | W
R4 | Team A | W
R1 | Team B | L
R2 | Team B | W
R3 | Team B | L
R4 | Team B | L

但我想像这样出局

RoundNo | Team A  | Team B  
R1 | W | L
R2 | L | W
R3 | W | L
R4 | W | L

我已根据建议更新了查询,但其显示为

之后的情况并非如此
RoundNo | Team | Team A  | Team B  
R1 | Team A | W | 0
R1 | Team B | 0 | L
R2 | Team A | L | 0
R2 | Team B | 0 | W
R3 | Team A | W | 0
R3 | Team B | 0 | L
R4 | Team A | W | 0
R4 | Team B | 0 | L

2 个答案:

答案 0 :(得分:0)

我知道了 - 我刚从开场SELECT和GROUP BY

中删除了Team

答案 1 :(得分:0)

SELECT Season, RoundNo, 
       MAX(CASE WHEN Team = 'Team A' THEN WL ELSE 0 END) as Team_A,
       MAX(CASE WHEN Team = 'Team B' THEN WL ELSE 0 END) as Team_B
FROM `MatchDetails2017` 
WHERE Season = 2017
GROUP BY RoundNo