I have read most of the posts on stackoverflow on how to do a pivot table but all of the posts show examples with prior knowledge of the columns. How do you construct a query if you have no knowledge of what the columns will be. here is some sample data:
id column value Row
1 age 13 1
2 height 55 1
3 fav number NULL 1
4 siblings 4 1
5 age 55 2
6 height 54 2
7 fav number 12 2
I am looking for this output:
row age height fav number siblings
1 13 55 NULL 4
2 55 54 12 NULL
As you can see there is no row 2 is missing an entry for siblings. The column names are unknown at the time of the query. How would you make this query.
I don’t see any way you can just write some fancy SELECT query to get what you want. You’re going to have to do some pre-processing.
You have to be executing this MySQL query from some sort of program, application, script, etc. Not sure what the language is, but here’s what I would do in PHP:
This will put all the data into a format you want in an array in PHP.
For example, after running this algorithm on the sample data you provided above, you would be able to do:
Which would output 55.
OR if your database isn’t being updated in real time (you have a bunch of data that you’d like to reformat once, rather than continuously), you could extend the script above to also have some “CREATE TABLE”, “INSERT INTO” queries that basically recreate the table in the format you’re looking for.
Furthermore, if you ARE receiving data in realtime, you can still write the script described above, but you’d just want to remove the rows from the original table as you processed them, and then just run the script whenever data is being put into the original table.