2015-08-08 65 views
0

我有一個數據庫表中象下面這樣:SQL查詢顯示列中的列項目?

----------------------------- 
| ID | Item1 | Item2 | Item3| 
----------------------------- 
| 1 | A1 | B3 | C1 | 
| 2 | A2 | B3 | C2 | 
| 3 | A1 | B2 | C2 | 
| 4 | A2 | B1 | C1 | 
----------------------------- 

我想顯示其計數表中的項目,如下面:

--------------- 
| item | count| 
--------------- 
| A1 | 2 | 
| A2 | 2 | 
| B1 | 1 | 
| B2 | 1 | 
| B3 | 2 | 
| C1 | 2 | 
| C2 | 2 | 
--------------- 

這可能嗎?如果是,查詢如何?到目前爲止,我只管理一個項目的foreach這樣來顯示它一個:

------------------ 
| Item1 | Count | 
------------------ 
SELECT COUNT(*) AS `Count` , `Item1` FROM `table` GROUP BY `Item1`; 

------------------ 
| Item2 | Count | 
------------------ 
SELECT COUNT(*) AS `Count` , `Item2` FROM `table` GROUP BY `Item2`; 

------------------ 
| Item3 | Count | 
------------------ 
SELECT COUNT(*) AS `Count` , `Item3` FROM `table` GROUP BY `Item3`; 
+0

首先正常化您的架構 – Strawberry

+0

應該確定@Strawberry。如果他有5個ID#1的項目,他可以有2行,Item1和Item2填入第二個,不是? – Drew

+0

只是在開玩笑Jess,清理架構。如果你想知道如何只是問 – Drew

回答

0

使用union allgroup by

select item, count(*) 
from ((select item1 as item from `table`) union all 
     (select item2 as item from `table`) union all 
     (select item3 as item from `table`) 
    ) t 
group by item 
order by item; 
+0

謝謝@GordonLinoff –