0

假设我有一个名为“matches”的表,我在其中保存了一场足球比赛中的 2 支球队。

-------------------------
| home_club | away_club |
-------------------------
|           |           |
-------------------------

我有一个查询,它通过 UNION 返回该表中的所有俱乐部,包括主队和客队俱乐部:

SELECT home_club AS clubs FROM matches UNION SELECT away_club FROM matches

现在我有一个名为“clubs”的结果集,我希望计算每个结果集出现在“matches”表中的次数。我该怎么做呢?

4

3 回答 3

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
于 2013-11-04T18:59:49.480 回答
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

于 2013-11-04T19:08:41.573 回答
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
于 2013-11-04T19:01:36.493 回答