7

Let's say I have some data, either in a SQL Server 2008 table or a [table]-typed variable:

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

I want to retrieve the data as a result set that looks like this:

author_id     review_id     1     2     3     4     5
88540         99001         719   720   721   722   723
36414         24336         302   303   304   305   306

I suspect the PIVOT operator is what I need (according to this post, anyway), but I can't figure out how to get started, especially when the number of question_id rows in the table can vary. In the above example, it's 5, but in another query the table might be populated with 7 distinct questions.

4

5 回答 5

9

实际上,您最好在客户端执行此操作。假设您正在使用 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;
于 2009-11-05T00:48:32.327 回答
3

Here you have great example and explanation.

In your case it would be like this:

SELECT author_id, review_id, [1], [2], [3], [4], [5]
FROM 
    (
        SELECT author_id, review_id, question_id, answer_id
        FROM the_table
    ) up
PIVOT (MAX(answer_id) FOR question_id IN ([1],[2],[3],[4],[5])) AS pvt
于 2009-11-05T00:51:10.887 回答
2
SELECT author_id, review_id, [1], [2], [3], [4], [5]
FROM 
    (
        SELECT author_id, review_id, question_id, answer_id
        FROM the_table
    ) up
PIVOT (MAX(answer_id) FOR
于 2012-03-07T09:39:58.767 回答
0

See this answer

Basically, you pre-inspect the data to get the columns and then dynamically generate the SQL using the dynamic pivot list. There's really no non-dynamic way, because the definition of the columns in the set you want to return is not fixed.

于 2009-11-05T00:52:10.667 回答
0
select * 
from @t pivot
(
    max(answer_id) for question_id in ([1],[2],[3],[4],[5])
) pivotT

改变列表 ([1],[2],[3],[4],[5]) 的唯一方法是在字符串中(动态)构建此查询,然后执行它。

于 2009-11-05T00:47:54.167 回答