0

I'm also new to MySQL.

This link has a good answer: How to select Column value as Column name with conditions in SQL table

Please refer to the link as this question is related to it. What if I don't know the field values, say, I don't know the values under the Field column. How will achieve the same result?

For clarification, my question is not the same with the pivot. In the pivot thread, you still need to indicate the name of the field values (e.g. Gender, Age, etc.). But what if you don't know the Field values?

The solution I chose was the following:

SELECT name,
       MAX(CASE WHEN field = 'Gender' THEN value END) gender,
       MAX(CASE WHEN field = 'Age' THEN value END) age
  FROM customers
 GROUP BY name

Yet, what if I don't know the field names? How can I achieve something like this?

SELECT name,
           MAX(CASE WHEN field THEN value END) field
      FROM customers
     GROUP BY name

I was thinking of looping the max, but it will just make everything more complicated. Any kind of help will be appreciated. Thanks!

JJ Labajo
  • 296
  • 1
  • 16
  • Possible duplicate of [MySQL pivot table](https://stackoverflow.com/questions/7674786/mysql-pivot-table) – Madhur Bhaiya Oct 24 '18 at 17:11
  • "For clarification, my question is not the same with the pivot. In the pivot thread, you still need to indicate the name of the field values (e.g. Gender, Age, etc.). But what if you don't know the Field values?" – JJ Labajo Oct 24 '18 at 17:19
  • You should really consider handling these requirements in your application code (eg: PHP, Java, C++ etc). RDBMS/SQL is not suited for generating dynamic columns – Madhur Bhaiya Oct 24 '18 at 17:20
  • So it's not possible? Well then, I guess somebody's gonna make a magic in PHP. Thank you. – JJ Labajo Oct 24 '18 at 17:23
  • I am not saying that it is not possible. It can be done but will be extremely verbose and seriously not the right way – Madhur Bhaiya Oct 24 '18 at 17:24
  • This is called a dynamic pivot. You should be able to find solutions if you google "MySQL dynamic pivot". – Gordon Linoff Oct 24 '18 at 22:42

0 Answers0