2009-04-24 99 views
1

源表:的SQL Server PIVOT帮助

Create Table ExamAnswers 
{ 
    StudentID varchar(12), 
    QuestionID int, 
    Answer char(1) 
} 

,这将充满

Bob 1 a 
Bob 2 c 
... 
Bob 100 b 
Chris 1 c 
Chris 2 d 
... 
Chris 100 null 

等,约500名学生。

Chris没有完成考试,但第100个问题被存储为空,因此可以保证每个学生都有100行,但实际答案为空或字符。

如果这有什么差别,答案是{A,B,C,d,E,F}

这种设置对于实际考试申请的伟大工程,并将其标记是微不足道的。

现在我有一个报告要求,对于审计的目的,我需要制作一个表格,看起来像这样:

ID 1 2 ... 100 
Bob a c ... b 
Chris c d ....null 

所以我花了半天时间阅读有关旋转功能,我只是不没办法。

这是我读过的最难读的文档。

首先,它需要和聚合函数 - 我应该在这里聚合到底是什么?

我想,这仅仅是对最简单的使用旋转功能,有可能是的,我不能在任何地方找到一个体面的例子。帮帮我!

回答

1

确定解决它。 MAX或MIN将在char字段上工作。 所以:

Create Table ExamAnswers 
{ 
    StudentID varchar(12), 
    QuestionID int, 
    Answer char(1) 
} 

由于最初创建

然后

SELECT StudentID, [1] as Q1, [2] as Q2, [3] as Q3, [4] as Q4, [5] as Q5 
FROM 
(
SELECT StudentID, QuestionID, Answer 
FROM dbo.ExamAnswers 
) AS piv 
PIVOT 
(
MAX(Answer) 
FOR QuestionID IN ([1], [2], [3], [4], [5]) 
) AS chld 

混乱奠定在一个聚合的选择那里是聚集没有任何合乎逻辑的理由。我应该提到StudentID和QuestionID形成一个复合键,因此对于任何给定的SID和QID对,只有一个可能的Answer值。

3

看看这篇文章: Using PIVOT and UNPIVOT

报价:

The following is annotated syntax for PIVOT. 

SELECT <non-pivoted column> , 

    [first pivoted column] AS <column name> , 

    [second pivoted column] AS <column name> , 

    ... 

    [last pivoted column] AS <column name> 

FROM 

    (<SELECT query that produces the data>) 

    AS <alias for the source query> 

PIVOT 

( 

    <aggregation function>(<column being aggregated>) 

FOR 

[<column that contains the values that will become column headers>] 

    IN ([first pivoted column] , [second pivoted column] , 

    ... [last pivoted column]) 

) AS <alias for the pivot table> 

<optional ORDER BY clause> 

正如你可以看到有一定的聚集功能(列被聚合)。 因此,表中的Answer列必须是整数(小数等),而不是char(1)。

EDIT:MIN()和MAX()为char()数据类型工作。

你的表可以是这样的:

Create Table ExamAnswers 
(
    StudentID varchar(12) NOT NULL, 
    QuestionID int NOT NULL, 
    Answer int 
) 

和SELECT语句PIVOT,那给你需要将结果:

SELECT StudentID, [1] as Q1, [2] as Q2, [3] as Q3, [4] as Q4, [5] as Q5 
FROM 
(
SELECT StudentID, QuestionID, Answer 
FROM dbo.ExamAnswers 
) AS piv 
PIVOT 
(
AVG(Answer) 
FOR QuestionID IN ([1], [2], [3], [4], [5]) 
) AS chld 
+0

Answer是一封信。它不是一个整数。我不能写封信。我不能SUM一个,我不想要一个COUNT。如果这封信是'a',我希望看到'a'。为什么这很难? – 2009-04-25 02:15:35