Skip to content
Advertisement

Row as column in mysql without using function

I am wodering is it possible to use a pivot table to make the col as rows without using any mysql functions and GROUP AS.

Here’s the table

+----+------+------+------+
| id | col1 | col2 | col3 |
+----+------+------+------+
|  1 |    1 |    2 |    6 |
|  2 |    7 |    4 |    8 |
|  3 |    4 |    1 |    5 |
+----+------+------+------+

Here’s the desired output iam looking for. The header is the id

+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 1 | 7 | 4 |
| 2 | 4 | 1 |
| 6 | 8 | 2 |
+---+---+---+  

Advertisement

Answer

This is painful, but you can do:

select max(case when id = 1 then col end) as id_1,
       max(case when id = 2 then col end) as id_2,
       max(case when id = 3 then col end) as id_3       
from ((select id, col1 as col, 1 as which from t) union all
      (select id, col2 as col, 2 as which from t) union all
      (select id, col3 as col, 3 as which from t)
     ) ic
group by which;

Note that this only works for the data that you have provided. If you have additional columns or rows, you would need to modify the query.

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement