2013-11-04 67 views
0

假設我有一張名爲「比賽」的表格,我在這裏保存了來自足球比賽的2支球隊。從一組選定的2個統一列中計數實例

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

而且我有一個返回所有的俱樂部從該表的查詢,無論是主場還是客場俱樂部通過UNION:

SELECT home_club AS clubs FROM matches UNION SELECT away_club FROM matches 

現在我有所謂的「俱樂部」一個結果集,我希望來計算每個出現在「匹配」表中的次數。我如何去做這件事?

回答

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

+0

這個作品很棒!謝謝 – Alternatex

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 
+0

只需要添加一個GROUP BY子句,它的工作原理。謝謝。 – Alternatex

+0

是的,我的意思是,忘了它。 – Tilak

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 
+0

我認爲這隻會計算他們在「俱樂部」結果集中但不在比賽表中的實例的數量。它所返回的每行都是1s。 – Alternatex

+1

查看是否將'UNION'改爲'UNION ALL'(以防止刪除重複的俱樂部名稱)是否有效。 – StyxUT

相關問題