2014-11-24 125 views
0

helo, 我想從表wp_formmaker_submits轉置一個名爲element_label的列。MYSQL Select Case Row to Column

原始表是

+---------+---------------+------------------+----------+ 
| FORM_ID | ELEMENT_LABEL | ELEMENT_VALUE | GROUP_ID | 
+---------+---------------+------------------+----------+ 
|  10 |    1 |  18-11-2014 |  1 | 
|  10 |    2 |   Logistic |  1 | 
|  10 |    3 | Warehouse Supply |  1 | 
|  10 |    4 |    Red |  1 | 
|  10 |    1 |  19-11-2014 |  2 | 
|  10 |    2 | Transportation |  2 | 
|  10 |    3 |   Vehicle |  2 | 
|  10 |    4 |   Green |  2 | 
+---------+---------------+------------------+----------+ 

我使用這個查詢

SELECT 
CASE WHEN element_label = 1 THEN element_value END a1, 
CASE WHEN element_label = 2 THEN element_value END a2, 
CASE WHEN element_label = 3 THEN element_value END a3, 
CASE WHEN element_label = 4 THEN element_value END a4 
FROM wp_formmaker_submits 

,我的結果是

+------------+----------------+------------------+--------+ 
|   A1 |    A2 |    A3 |  A4 | 
+------------+----------------+------------------+--------+ 
| 18-11-2014 |   NULL |    NULL | NULL | 
|  NULL |  Logistic |    NULL | NULL | 
|  NULL |   NULL | Warehouse Supply | NULL | 
|  NULL |   NULL |    NULL | Red | 
| 19-11-2014 |   NULL |    NULL | NULL | 
|  NULL | Transportation |    NULL | NULL | 
|  NULL |   NULL |   Vehicle | NULL | 
|  NULL |   NULL |    NULL | Green | 
+------------+----------------+------------------+--------+ 

如何去除NULL,所以我會得到像這樣的結果

+---------+----------+------------+----------------+------------------+-------+ 
| FORM_ID | GROUP_ID |   A1 |    A2 |    A3 | A4 | 
+---------+----------+------------+----------------+------------------+-------+ 
|  10 |  1 | 18-11-2014 |  Logistic | Warehouse Supply | Red | 
|  10 |  2 | 19-11-2014 | Transportation |   Vehicle | Green | 
+---------+----------+------------+----------------+------------------+-------+ 

回答

0

試試這個

SELECT form_id,group_id, 
MAX(CASE WHEN element_label = 1 THEN element_value END) as a1, 
MAX(CASE WHEN element_label = 2 THEN element_value END) as a2, 
MAX(CASE WHEN element_label = 3 THEN element_value END) as a3, 
MAX(CASE WHEN element_label = 4 THEN element_value END) as a4 
FROM tbl 
Group by form_id,group_id 

如果仍然有問題,然後PLZ分享sqlfiddle你的表模式。

+0

要求您在'CASE'之前添加'MAX'功能。 – Wanderer 2014-11-24 06:43:42

+0

[看這裏的小提琴演示](http://sqlfiddle.com/#!2/882a13/8) – Wanderer 2014-11-24 06:44:15

+0

它工作正常。因爲它正在生成相應的結果,並且使用MAX不會生成所需的結果 – 2014-11-24 06:50:22

1

添加一個聚合函數,如

MAX(CASE WHEN element_label = 1 THEN element_value END) a1