sql >> Base de Datos >  >> RDS >> Sqlserver

Usando PIVOT en SQL Server 2008

En realidad, sería mejor que hicieras esto en el cliente. Suponga que está utilizando Reporting Services, obtenga los datos según su primer conjunto de resultados y muéstrelos usando una Matriz, con author_id y review_id en el Grupo de Filas, question_id en el Grupo de Columnas y MAX(answer_id) en el medio.

Una consulta es factible, pero necesitaría SQL dinámico en este momento.

...algo como:

DECLARE @QuestionList nvarchar(max);
SELECT @QuestionList = STUFF(
(SELECT ', ' + quotename(question_id)
FROM YourTable
GROUP BY question_id
ORDER BY question_id
FOR XML PATH(''))
, 1, 2, '');

DECLARE @qry nvarchar(max);
SET @qry = '
SELECT author_id, review_id, ' + @QuestionList + 
FROM (SELECT author_id, review_id, question_id, answer_id
      FROM YourTable
     ) 
PIVOT
(MAX(AnswerID) FOR question_id IN (' + @QuestionList + ')) pvt
ORDER BY author_id, review_id;';

exec sp_executesql @qry;