我有一个如下所示的表格。
**id | location**
1 | East Flow
2 | East Level
3 | East Pressure
我想在Mysql中使用select语句将上表转换如下。
1 | 2 | 3
East Flow | East Level | East Pressure
我使用的是MySql 5.5 请帮忙。
最佳答案
如果 Id 列的计数是固定或已知的,则使用 CASE
表达式。
查询
select max(case when id = 1 then location end) as `1`,
max(case when id = 2 then location end) as `2`,
max(case when id = 3 then location end) as `3`
from your_table;
如果id
列的计数未知,那么您可能需要使用动态sql。
查询
select
group_concat(distinct
concat(
'max(case when id = ',
id,' then location end) as `', id,'`'
)
) into @sql
from your_table;
set @sql = concat('select ', @sql, ' from your_table');
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;
关于mysql - 在mysql中选择行到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32989616/