简体   繁体   English

在mysql中选择行到列

[英]Select rows to columns in mysql

I have a table as shown below. 我有一张桌子,如下所示。

**id | location**
1  | East Flow
2  | East Level
3  | East Pressure

I would like to convert the above table as follows using select statement in Mysql. 我想使用Mysql中的select语句按如下方式转换上表。

1          | 2           | 3  
East Flow  | East Level  | East Pressure

I am using MySql 5.5 Please help. 我正在使用MySql 5.5,请帮助。

Use a CASE expression if the count of Id column is fixed or known. 如果Id列的计数是固定的或已知的,请使用CASE表达式。

Query 询问

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;

If the count of id column is unknown then you may need to use dynamic sql. 如果id列的计数未知,则可能需要使用动态sql。

Query 询问

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;

SQL Fiddle SQL小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM