There is no single syntax that will pivot this data in that way.
The SQL language (for any database) has firm requirement that you know the number and type of each column in the results at query compile time. This is needed in order for the database engine to determine correct permissions and compute the execution plan. Even SELECT *
queries meet this requirement, as the number and types of columns in the tables used by the query are fixed and known (at least for the life of a single query).
What this question asks to do breaks that requirement. The column headers are determined by the data, and therefore the database engine can't know how many columns it needs for the results until after the query begins to execute.
The only way to get around this is to break the query into three separate steps:
- Run a simpler query to determine the column headings for the final results.
- Use the results from #1 to build a new SQL string on the fly
- Execute the query from #2 and return it's results to the user.