I have a MySQL database where the table was set up to store the data in a vertical fashion:
Userid -- Field -- Data
186 30 New York
186 31 Phone
186 32 Delta
187 30 Los Angeles
187 31 Website
187 32 US Air
I am able to select columns if they are already horizontal but want to be able to organize the output so it looks like this:
Userid -- Data30 -- Data31 -- Data32
186 New York Phone Delta
187 Los Angeles Website US Air
How do I say “Select DATA30 to show for this column but only if FIELD equals 30”?
This is a classic pivot table. Using
MAX()aggregates andGROUP BYwithCASE, you can convert the rows to columns. This will only work properly if the values forFieldare limited and well-defined.The purpose of the
MAXaggregate is only to eliminateNULLfor each value, so instead of 3 rows perUseridwith only one of the values non-null, they are collapsed into a single row.