我得到了这个视图(这是示例数据):
HomeTeam HomeTeamScore AwayTeamScore AwayTeam
---------------------------------------------------------------
Middlesbrough 3 1 Manchester United
Manchester City 1 1 Liverpool
Liverpool 2 0 Middlesbrough
Manchester United 3 2 Manchester City
我计算主队以这种方式得分的数量(类似于我计算客场球队得分的数量):
SELECT HomeTeam, SUM (HomeTeamScore) AS CountGoals
FROM vW_Match
GROUP BY HomeTeam ORDER BY CountGoals DESC
我如何计算球队积分?如果结果吸引两支球队获得1分,如果第一支球队获得更多进球然后离开球队,则获得3分,如果客队得分更多,则得到3分?
答案 0 :(得分:3)
你可以尝试一下
;WITH temps AS
(SELECT HomeTeam AS Team,
case when HomeTeamScore = AwayTeamScore then 1
when HomeTeamScore > AwayTeamScore then 3
ELSE 0
end AS Point
FROM vW_Match
UNION ALL
SELECT AwayTeam AS Team,
case when HomeTeamScore = AwayTeamScore then 1
when AwayTeamScore > HomeTeamScore then 3
ELSE 0
end AS Point
FROM vW_Match
)
select t.Team, sum(t.Point) as TotalPoint
from temps t
group by t.Team
答案 1 :(得分:2)
试试这个:
SELECT team, sum(points) from (
select HomeTeam as team,
case
when HomeTeamScore > AwayTeamScore then 3
when HomeTeamScore = AwayTeamScore then 1
ELSE 0
end as points
FROM vW_Match
UNION ALL
select AwayTeam as team,
case
when HomeTeamScore > AwayTeamScore then 0
when HomeTeamScore = AwayTeamScore then 1
ELSE 3
end as points
FROM vW_Match
) t
GROUP BY team
答案 2 :(得分:1)
使用CASE语句比较每个团队的结果,您可以获得每场比赛的相应得分:
select HomeTeam,
HomeTeamScore,
case when HomeTeamScore = AwayTeamScore then 1
when HomeTeamScore > AwayTeamScore then 3
when HomeTeamScore < AwayTeamScore then 0
end as HomeTeamPoints,
AwayTeam,
AwayTeamScore,
case when AwayTeamScore = HomeTeamScore then 1
when AwayTeamScore > HomeTeamScore then 3
when AwayTeamScore < HomeTeamScore then 0
end as AwayTeamPoints
from vW_Match
这将为不同列中的两个团队提供结果。