我有一张包含游戏列表的表格,它有团队ID和游戏中的分数。
这是表结构。
ID HOMETEAM HOMETEAMSCORE AWAYTEAM AWAYTEAMSCORE
我需要获得2个特定球队的比赛记录。例如,对于第1队和第2队,我需要输出为1-3,这意味着第1队已经赢得了一次对阵第2队,第2队已经赢得3次对阵第1队。
我正在使用下面的SQL,它在一定程度上起作用。但是对于尚未开始的比赛,我需要输出为0-0(得分为0-0)。
SELECT least(homeTeam, awayTeam) team1,
greatest(homeTeam, awayTeam) team2,
sum(case when awayTeam > homeTeam
then case when homeTeamScore > awayTeamScore then 1 else 0 end else case when homeTeamScore > awayTeamScore then 0 else 1 end
end) team1Wins,
sum(case when hometeam > awayteam
then case when homeTeamScore > awayTeamScore then 1 else 0 end else case when homeTeamScore > awayTeamScore then 0 else 1 end
end) team2Wins
FROM ow_sports_games
GROUP BY least(homeTeam, awayTeam),
greatest(homeTeam, awayTeam)
还有什么比这更好的方法来获得更好的SQL吗?
SQL小提琴:http://sqlfiddle.com/#!2/10326/4/1
修改
一些示例数据可以更详细地解释我的要求:
HOMETEAM HOMETEAMSCORE AWAYTEAM AWAYTEAMSCORE
18 1 22 0
22 2 18 1
18 3 22 2
12 0 13 0
对于18,22队,输出应为2-1,因为18队有2场胜利,22队有1场
对于12队和13队,输出应为0-0,因为没有比赛结束。
OUTPUT示例解释整体情况:
HomeTeam AwayTeam Records
18 22 2-1
22 18 1-2
12 13 0-0
答案 0 :(得分:1)
这与问题陈述中的输出相匹配(前3列是相同的,接下来的两列是用于排序的,并确保我们在没有玩的时候考虑但是有记录。请参阅http://sqlfiddle.com/#!2/10326/43
SELECT DISTINCT hometeam, awayteam
, CONCAT(IF(hometeam = LEAST(hometeam, awayteam),team1wins, team2wins),' - ', IF(awayteam = LEAST(hometeam, awayteam),team1wins, team2wins)) AS Head2HeadRecord
, CONCAT(LEAST(hometeam, awayteam), GREATEST(hometeam, awayteam)) AS surrogateSort
, notplayed
FROM ow_sports_games
JOIN (SELECT LEAST(hometeam, awayteam) AS team1
,GREATEST(hometeam, awayteam) AS team2
,SUM(IF(LEAST(hometeam, awayteam) = hometeam AND homeTeamScore > awayTeamScore, 1,
IF(LEAST(hometeam, awayteam) = awayteam AND awayTeamScore > homeTeamScore,1,0)
)
) AS team1Wins
,SUM(IF(GREATEST(hometeam, awayteam) = hometeam AND homeTeamScore > awayTeamScore, 1,
IF(GREATEST(hometeam, awayteam) = awayteam AND awayTeamScore > homeTeamScore,1,0)
)
) AS team2Wins
,SUM(IF(homeTeamScore=0 AND awayTeamScore=0,1,0)) AS notPlayed
FROM ow_sports_games
GROUP BY team1, team2) AS trecords
ON LEAST(hometeam, awayteam) = team1
AND GREATEST(hometeam, awayteam) = team2
ORDER BY surrogateSort, hometeam,awayteam;