0

我正在尝试列出每支球队在总比赛中输掉的比赛比例。

我尝试了以下方法,但似乎不起作用:

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;

我在最后一行编写函数的方式有问题吗?

关系图供参考:

在此处输入图像描述

4

1 回答 1

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
于 2013-05-10T14:04:17.157 回答