如何将单行转换为一列?

时间:2015-03-04 10:39:59

标签: valueconverter row-value-expression

如何将一行的列转换为一行?

将数据放在表格中如下:

+------+------+------+------+
| col1 | col2 | col3 | col4 |
+------+------+------+------+
|  a1  |  a2  |  a3  |  a4  |
+------+------+------+------+

必需的输出:行中的所有值都应该在单列中,如下所示。

+---------------+
|   All_cols    |
+---------------+
|  a1,a2,a3,a4  |
+---------------+

与图片类似:此处mytable总是有一条记录,所以我需要输出如下。

enter image description here

希望避免使用sql,因为它需要多个连接:

select a1.name from  accounts a1 where a1.id='658f3b73-8260-5a7a-ae7e-54c25deded36'

union

Select a2.name from accounts a1
left join accounts a2 on a1.id=a2.parent_id where a1.id='658f3b73-8260-5a7a-ae7e-54c25deded36'

union

Select a3.name from accounts a1
left join accounts a2 on a1.id=a2.parent_id
left join accounts a3 on a2.id=a3.parent_id where a1.id='658f3b73-8260-5a7a-ae7e-54c25deded36'

union

Select a4.name from accounts a1
left join accounts a2 on a1.id=a2.parent_id
left join accounts a3 on a2.id=a3.parent_id
left join accounts a4 on a3.id=a4.parent_id where a1.id='658f3b73-8260-5a7a-ae7e-54c25deded36'

union

Select a5.name from accounts a1
left join accounts a2 on a1.id=a2.parent_id
left join accounts a3 on a2.id=a3.parent_id
left join accounts a4 on a3.id=a4.parent_id
left join accounts a5 on a4.id=a5.parent_id where a1.id='658f3b73-8260-5a7a-ae7e-54c25deded36'

1 个答案:

答案 0 :(得分:0)

你可以在四个单一的电话上发出UNION

SELECT col1 FROM mytable
UNION
SELECT col2 FROM mytable
UNION
SELECT col3 FROM mytable
UNION
SELECT col4 FROM mytable

将输出

enter image description here

你说那个

  

mytable总是有一条记录。

请注意,如果您有多条记录,最好在上面的每个WHERE语句中使用相同的SELECT条件。