我有两个带有以下数据的 postgresql 表
[teams]
[id][team_name]
1 team 1
2 team 2
3 team 3
[matches]
[participant 1][participant 2]
1 3
2 1
3 2
比赛表引用团队 ID。
我正在尝试计算每支球队参加比赛的次数,以便可以显示每支球队参加的比赛总数。我已经尝试使用 UNIONS、COUNT 等几个小时来执行此操作,但没有成功。如果您能提供任何帮助来解决此问题,我将不胜感激。
如您所见,
matches
内的每条记录实际上是两条记录:participant 1
有一个 home 匹配(让它成为 kind = 1
),而 participant 2
有一个 guest 匹配(kind = 2
)。
到目前为止一切顺利,让我们复制每条记录(在 cte
的帮助下),然后我们可以使用旧的 count
和 group by
with games as (
select [participant 1] id,
1 kind -- home matches
from Matches
union all
select [participant 2] id,
2 kind -- guest matches
from Matches
)
select t.team_name,
count(1) total_matches
from games g
join teams t on (t.id = g.id)
group by t.id,
t.team_name
order by t.team_name
将
teams
与 matches
连接两次(通过 participant_1
和 participant_2
),合并结果,然后进行分组/计数。
select id, count(id) matches_cnt from
(
select id from teams join matches on id = participant_1
union all
select id from teams join matches on id = participant_2
) t
group by id;