假设我有一些数据,无论是在 SQL Server 2008 表中还是在 [表] 类型的变量中:
author_id review_id question_id answer_id
88540 99001 1 719
88540 99001 2 720
88540 99001 3 721
88540 99001 4 722
88540 99001 5 723
36414 24336 1 302
36414 24336 2 303
36414 24336 3 304
36414 24336 4 305
36414 24336 5 306
我想将数据检索为如下所示的结果集:
author_id review_id 1 2 3 4 5
88540 99001 719 720 721 722 723
36414 24336 302 303 304 305 306
我怀疑 PIVOT 运算符是我需要的(根据 this post ,无论如何),但我不知道如何开始,尤其是当 的数量时question_id 表中的行可以不同。在上面的示例中,它是 5,但在另一个查询中,该表可能填充了 7 个不同的问题。
最佳答案
实际上,您最好在客户端执行此操作。假设您正在使用 Reporting Services,根据您的第一个结果集获取数据并使用矩阵显示它,在行组中使用 author_id 和 review_id,在列组中使用 question_id,在中间使用 MAX(answer_id)。
查询是可行的,但您现在需要动态 SQL。
...就像是:
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;
关于sql - 在 SQL Server 2008 中使用 PIVOT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1677645/