1

I have a table with such structure:

option_name | option_value
==========================
name        | GK
age         | 50
some_opt    | true

Can I write a query, that will rotate the table and get me results like this:

name  |  age   | some_opt
=========================
GK    |  50    | true

Also how would the query look, if each option would have a group id:

group_id  | option_name  | option_value
=======================================
1         | name         | GK
1         | age          | 50
2         | name         | ML
2         | age          | 34
1         | some_opt     | true

To provide such results:

group_id  | name  | age  | some_opt
=====================================
1         | GK    | 50   | true
2         | ML    | 34   | NULL

As per the other answer, my problem (with grouped parameters) can be solved with the following: http://buysql.com/mysql/14-how-to-automate-pivot-tables.html

Thanks!

Giedrius
  • 1,370
  • 3
  • 14
  • 37
  • This is called pivoting and answers to the linked duplicate question describe how to do a static (column names are fixed) or a dynamic (column names are fetched from the table) pivot in MySQL. However, in many cases it is more effective to do such transformations in the application code. – Shadow Feb 17 '17 at 16:22
  • Hi, I can see it's a similar problem, but in my problem the `option_name` values are now known, so I can't do `SELECT .. as 'name'` – Giedrius Feb 17 '17 at 16:22
  • This looks like a homework assignment? – TerNovi Feb 17 '17 at 16:22
  • @TerNovi It is for my work project I am working on currently. I can achieve this with PHP, but was wondering if there was a clean solution using only MySQL to get the data in the right format. – Giedrius Feb 17 '17 at 16:23

0 Answers0