假设我有一个名为“匹配”的表格,我可以从足球比赛中保存2支球队。
-------------------------
| home_club | away_club |
-------------------------
| | |
-------------------------
我有一个查询,通过UNION返回该表中的所有俱乐部,包括主场和客场俱乐部:
SELECT home_club AS clubs FROM matches UNION SELECT away_club FROM matches
现在我有一个名为“俱乐部”的结果集,我希望计算每个在“匹配”表中出现的次数。我该怎么做呢?
答案 0 :(得分:1)
尝试以下
select sum(count) as Matches, Club from
(select count(*) as count, home_club as Club from matches group by home_club
union all
select count(*) as count, away_club as Club from matches group by away_club ) a
group by a.clubs
答案 1 :(得分:1)
如果您想知道每个在matches
表中出现的次数,那么您需要删除子查询中的union
。 union
将删除重复项。
以下是如何计算:
select club, count(*) as NumAppears
from (SELECT home_club AS club FROM matches
UNION ALL
SELECT away_club FROM matches
) m
group by club;
请注意,UNION
已替换为UNION ALL
。
答案 2 :(得分:0)
SELECT
M.clubs,
COUNT(M.clubs) [count]
FROM
(
SELECT
home_club AS clubs
FROM
matches
UNION ALL
SELECT
away_club
FROM
matches
) M
GROUP BY
M.clubs