Skip to content
Advertisement

Creating a PIVOT with dynamic rows and columns – SQL Server 2016

First, let’s define the tables:

The following query gets all the answers with questions for a specific reviewee:

And the output looks more or less like this:

What I want is output that looks like this:

The number of questions and reviews/review_dates is not known until runtime.

I am ultimately writing this query for a VB/ASP front end, so if it is easier to handle some of the dynamism through VB, that’s doable. It doesn’t have to be a purely SQL solution.

EDIT I tried the following query:

It created the correct columns, but NULL results in the date columns

Advertisement

Answer

Okay, it turned out the last query was on the right track, the problem was the automatic date to string conversion implicitly happening from QUOTENAME was causing no matches in the IN clause.

Final correct query:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement