HELO, 我试图从表wp_formmaker_submits转置一个名为element_label的列。
原始表是
+---------+---------------+------------------+----------+
| 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 :(得分:1)
添加聚合函数,例如
MAX(CASE WHEN element_label = 1 THEN element_value END) a1
答案 1 :(得分: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上共享你的表模式。