簡體   English   中英

在mysql中選擇行到列

[英]Select rows to columns in mysql

我有一張桌子,如下所示。

**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;

SQL小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM