0

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.

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

I am using MySql 5.5 Please help.

1 Answer 1

2

Use a CASE expression if the count of Id column is fixed or known.

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.

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Thanks for your reply. In my case the count of id column is unknown and not fixed. Any idea?
Hi, This solution is working. Thank you for that. But facing one more issue, when I run the dynamic SQL in MySql workbench it works perfectly, but when I run the same using eclipse Datasource explorer, I am getting syntax error. Any idea?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.