我正在尝试列出每支球队在比赛总比赛中输掉比赛的比率。
我已经尝试了以下但它似乎不起作用:
select teams.name as Name,
Lost
from teams
join matches on teams.name in (matches.home, matches.away)
group by teams.name
having (1 - (matches.winner / (count (matches.home) + count (matches.away)))) as Lost;
我在最后一行编写函数的方式有问题吗?
参考关系图:
答案 0 :(得分:2)
HAVING
子句用于在发生任何分组后过滤结果集,而不是定义函数。
您需要为SELECT子句中返回的列编写所有逻辑。
SELECT T.NAME
,COUNT(M.*) AS MATCHES_PLAYED
,SUM(CASE WHEN M.WINNER = T.NAME THEN 1 ELSE 0 END) AS WINS
,SUM(CASE WHEN M.WINNER = T.NAME THEN 0 ELSE 1 END) AS LOSSES
,SUM(CASE WHEN M.WINNER = T.NAME THEN 1 ELSE 0 END)/COUNT(M.*) AS WIN_PERCENT
,SUM(CASE WHEN M.WINNER = T.NAME THEN 0 ELSE 1 END)/COUNT(M.*) AS LOSS_PERCENT
FROM TEAMS T
INNER JOIN
MATCHES M
ON T.NAME = M.HOME
OR T.NAME = M.AWAY
GROUP BY
T.NAME