我正在努力完成以下任务 -
我有2个足球队的桌子(不是由我创建的,这是我必须使用的):
won_matches-
columns: team_id | match_name | scored_goals
lost_matches-
columns: team_id | match_name | scored_goals
teams_names-
team_id | team_name
(我不关心比赛名称或得分目标数量)
我需要做的是COUNT每个团队在won_matches表中有多少条目以及它在lost_matches表中有多少条目,然后将lost_matches的数量除以won_matches的数量,从而获得丢失/赢得比赛率。 然后,我需要为每个团队(或所有团队)及其团队名称提供此比率。
我试过这样的事情,但是根本不能起作用:
SELECT b. team_name, (SELECT COUNT(team_id)
FROM won_matches [***optional; WHERE team_id=37***]) / COUNT(a.team_id)*100 AS lost_won_ratio
FROM lost_matches a
join teams_names b on a.team_id=b.team_id
[***optional; WHERE a.team_id=37***]
非常感谢你的建议。
答案 0 :(得分:0)
尝试这样的事情:
select team_id, Won, count(*) as Matches, sum(scored_goals) as Goals
from
(select 1 as Won, Team_id, scored_goals from won_matches
union all
select 0 as Won, team_id, scored_goals from lost_matches) x
group by team_id, Won
答案 1 :(得分:0)
我认为类似的东西可以解决问题:
select team_id,
count(won), count(lost),
count(won)/(count(won)+count(lost)) as 'Win ratio' from
(
select True as won, NULL as lost, won_matches.* from won_matches
union all
select NULL as won, True as lost, lost_matches.* from lost_matches
) as S group by team_id
http://sqlfiddle.com/#!2/6dbaf/2(编辑:使用联接来显示团队名称)
请注意我没有考虑可能的抽奖比赛,因为我不知道这是如何存储在你的数据库中的。
编辑请注意我使用count(won)/(count(won)+count(lost))
作为计数比率公式。这似乎更符合逻辑。如果你坚持使用count(lost)/count(win)
,你必须处理除以0的情况......
答案 2 :(得分:0)
这样的事情应该有效。
SELECT tn.teamID, sum(won_matches.teamID ) as WON, sum(lost_matches.teamID ) as LOST,(sum(won_matches.teamID )/sum(lost_matches.teamID )) as WLratio
From teams_names AS tn LEFT JOIN won_matches ON tn.teamID = won_matches.teamID LEFT JOIN lost_matches ON tn.teamID = lost_matches.teamID