我需要选择所有匹配并在指定的比赛中按团队进行分组。
问题是,在匹配中,我有2个外键到团队
1)host_id
2)guest_id
要选择两个团队,我选择比赛并加入:
JOIN
teams host ON matches.host_id = host.id
JOIN
teams guest ON matches.guest_id = guest.id
但我有问题如何将它们分组,以便对来自不同团队的匹配的所有统计数据进行合并。主人和客人都不会成倍增加 因为如果我按照host.name和guest.name对它们进行分组,我会像Team一样获得Team1的SUM,而像Team1一样获得Team1的SUM。
顺便说一下。欢迎stackoverflow;)
答案 0 :(得分:0)
创建一个子集合,用于获取所需的聚合,然后返回到主要语句。
(rest of your joins)
join
(select host.id, sum(score) totalscore,avg(gametime) average_gametime,sum(whateverelse)
from host
group by host.ID) a
on host.id = a.id
现在你可以调用a.totalscore,a.average_gametime或select子句中的任何其他内容
答案 1 :(得分:0)
你似乎想要一个团队在家里和客人时的匹配信息:
select t.id, count(*), sum(...), ...
from teams t join matches m
where t.id = m.home or t.id=m.guest
group by (t.id)
您的团队ID以外的比赛信息现在也可以分开给家庭和客人。例如匹配列home_score& away_score。然后你需要用“或”来获取那些信息:
select t.id,
case when when t.id = m.home then "home" when t.id = m.guest then "guest" end case) as role,
sum(*) as games_played,
sum(case when t.id = m.home then m.home_score when t.id = m.guest then m.home_guest end case) as total_score,
case when t.id = m.home then m.home_penalties when t.id = m.guest then m.home_penalties end case) as total_penalties,
...
这可以用较少的case表达式编写,但可能更慢:
select id, role, count(*), sum(score), sum(penalty)
from teams t
join (select home as team, "home" as role, m.home_score as score, m.home_penalty as penalty, ..., match.* from matches)
union
select away as team, "away" as role, m.away_score as score, m.away_penalty as penalty, ..., match.* from matches) m
on t.id = m.team
group by (t.id)
为了避免这些并发症,您可以保持一个团队是在家还是离开(角色)加上其在表中每场比赛的结果,并且只保留另一个表中匹配的团队配对,然后定义与其home_ / away_列的匹配作为他们的观点。