2013-04-30 93 views
5

我有一個mysql數據庫中的兩列,我想要統計兩個列中出現單個名稱的次數。 COUNT函數本身不適用於我,因爲它只計算一列中的總數。SQL計數值在多列中出現多少次?

MySQL的列:

+-----------------+--------------+ 
| Member1   | Member2  | 
+-----------------+--------------+ 
| John   | Bill   | 
| Bill   | John   | 
| Joe    | John   | 
| Bill   | Joe   | 
| John   | Steve  | 
+-----------------+--------------+ 

所需的輸出:

+-----------------+--------------+ 
| Member   |  Total | 
+-----------------+--------------+ 
| John   | 4   | 
| Bill   | 3   | 
| Joe    | 2   | 
| Steve   | 1   | 
+-----------------+--------------+ 

任何想法?謝謝!

+1

可能重複的[SQL,在多個列中計數,然後按組](http://stackoverflow.com/questions/12354207/sql-count-in-multiple-columns-then-group-by) – 2013-04-30 12:25:58

回答

10

您可以使用以下內容,將您的多列成員轉換爲使用UNION ALL的單個列。一旦它在單個列,那麼你可以申請聚合函數count

select member, count(*) Total 
from 
(
    select member1 as member 
    from yt 
    union all 
    select member2 
    from yt 
) d 
group by member 
order by total desc; 

SQL Fiddle with Demo

0

如果一個名字出現在1列2倍多,上面的SQL結果將是錯誤的。 在子查詢中使用「distinct」語句嘗試。