使用两个字段对结果进行分组

问题描述 投票:0回答:1

我有一个当地的体育联盟数据库(这与我解释询问的原因相关)。 在此我有一个 team_matches 表,并且在我的应用程序中提供了多种查看比赛的方法(按场地、按分区、按日期等)。这效果很好,其中大多数方法之一是能够显示一个选项页面,其中包含选项和比赛数量 - 以场地为例:

SELECT COUNT( me.scheduled_date ) AS 'number_of_matches', venue.id, venue.url_key, venue.name
FROM team_matches me
JOIN seasons season ON season.id = me.season
JOIN venues venue ON venue.id = me.venue
WHERE ( season.id = 9 )
GROUP BY venue.id
ORDER BY venue.name ASC

如果我显示这些结果(场地名称和比赛数量),我会得到如下内容: Venues with number of matches displayed

问题是这些选项之一是按团队查看 - 我还没有找到显示此选项的方法,因为团队可能位于 home_team 或away_team 列中,而且我不确定如何显示可以在任一列中的团队列表以及计数,因为分组肯定必须按照团队出现在的任何列 - 这是否有意义? 提前感谢您的帮助!

sql mysql
1个回答
0
投票

由于球队可以是

home_team
away_team
,因此您需要考虑两者来计算每队的比赛次数。

SELECT 
    team.id, 
    team.name, 
    COUNT(*) AS number_of_matches
FROM (
    SELECT home_team AS team_id, scheduled_date
    FROM team_matches
    WHERE season = 9
    UNION ALL
    SELECT away_team AS team_id, scheduled_date
    FROM team_matches
    WHERE season = 9
) AS matches
JOIN teams AS team ON team.id = matches.team_id
GROUP BY team.id
ORDER BY team.name ASC;
© www.soinside.com 2019 - 2024. All rights reserved.