Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Setting Column Values as Column Names in MySQL Query Result



To set column values as column names in the query result, you need to use a CASE statement.

The syntax is as follows −

select yourIdColumnName,
max(case when (yourColumnName1='yourValue1') then yourColumnName2 else NULL
end) as 'yourValue1',
max(case when (yourColumnName1='yourValue2') then yourColumnName2 else NULL
end) as 'yourValue2',
max(case when yourColumnName1='yourValue3') then yourColumnName2 else NULL
end) as 'yourValue3’,
.
.
N
from valueAsColumn
group by yourIdColumnName
order by yourIdColumnName;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table valueAsColumn
   -> (
   -> UserId int,
   -> UserColumn1 varchar(10),
   -> UserColumn2 varchar(10)
   -> );
Query OK, 0 rows affected (0.75 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into valueAsColumn values(0,'John','A+');
Query OK, 1 row affected (0.18 sec)
mysql> insert into valueAsColumn values(0,'Carol','B');
Query OK, 1 row affected (0.17 sec)
mysql> insert into valueAsColumn values(0,'Sam','C');
Query OK, 1 row affected (0.17 sec)
mysql> insert into valueAsColumn values(1,'John','D');
Query OK, 1 row affected (0.20 sec)
mysql> insert into valueAsColumn values(1,'Carol','A');
Query OK, 1 row affected (0.20 sec)
mysql> insert into valueAsColumn values(1,'Carol','C');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using a select statement. The query is as follows −

mysql> select *from valueAsColumn;

The following is the output −

+--------+-------------+-------------+
| UserId | UserColumn1 | UserColumn2 |
+--------+-------------+-------------+
|      0 | John        | A+          |
|      0 | Carol       | B           |
|      0 | Sam         | C           |
|      1 | John        | D           |
|      1 | Carol       | A           |
|      1 | Carol       | C           |
+--------+-------------+-------------+
6 rows in set (0.00 sec)

Here is the query to set column value as column names −

mysql> select UserId,
   -> max(case when (UserColumn1='John') then UserColumn2 else NULL end) as 'John',
   -> max(case when (UserColumn1='Carol') then UserColumn2 else NULL end) as 'Carol',
   -> max(case when (UserColumn1='Sam') then UserColumn2 else NULL end) as 'Sam'
   -> from valueAsColumn
   -> group by UserId
   -> order by UserId;

The following is the output −

+--------+------+-------+------+
| UserId | John | Carol | Sam  |
+--------+------+-------+------+
|      0 | A+   | B     | C    |
|      1 | D    | C     | NULL |
+--------+------+-------+------+
2 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:25+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements