2016-09-15 70 views
1

我有一張如下所示的表格。如何使用MySql將列轉換爲表格的行

id  | name | place_1 | Place_2 | place_3 | 
------------------------------------------------------ 
12  | Anne | School |   |   | 
13  | Smith |   | church |   | 
14  | Mari | School |   | Temple | 
15  | Nash |   |   | Temple | 
16  | Narmada |   | Church | Temple | 

我想要做的是分別統計位置,並獲得一個表只有以下列。 就像Place_1,Place_2,Place_3。並使用存儲過程將列轉換爲行。

像下面

Place | count | 
------------------ 
Place_1 | 2  | 
Place_2 | 2  | 
Place_3 | 3  | 

誰能幫助我做到這一點?

+0

不要的地方總是出現在同一列或它們可以出現在任何列 - 例如沒有學校總是出現在PLACE_1? –

+0

任何時候你看到枚舉的列(比如'2'之上)都會響起警鈴。見正常化。 – Strawberry

+0

@ P.salmon是的。我認爲place_1是學校,place_2是教堂,place_3是廟宇。 – casper

回答

0
drop table if exists t; 
create table t(id int, name varchar(10), place_1 varchar(10), Place_2 varchar(10), place_3 varchar(10)); 
insert into t values 
(2  , 'Anne' , ' School' , null  , null ), 
(13  , 'Smith' , null  , 'church' , null ), 
(14  , 'Mari' , 'School' , null  , 'Temple'), 
(15  , 'Nash' , null  , null  , 'Temple'), 
(16  , 'Narmada' , null  , 'Church' , 'Temple'); 


select 'Place_1' as place,count(*) 'Count' from t where place_1 is not null 
union 
select 'Place_2' as place,count(*) from t where place_2 is not null 
union 
select 'Place_3' as place,count(*) from t where place_3 is not null 

結果

+---------+-------+ 
| place | Count | 
+---------+-------+ 
| Place_1 |  2 | 
| Place_2 |  2 | 
| Place_3 |  3 | 
+---------+-------+