从一组选定的2个统一列中计算实例

时间:2013-11-04 18:56:23

标签: sql

假设我有一个名为“匹配”的表格,我可以从足球比赛中保存2支球队。

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

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

SELECT home_club AS clubs FROM matches UNION SELECT away_club FROM matches

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

3 个答案:

答案 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表中出现的次数,那么您需要删除子查询中的unionunion将删除重复项。

以下是如何计算:

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