来源表:
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个问题存储为null,因此保证每个学生只有100行,但实际答案为空或字符。
如果有任何不同,答案在{a,b,c,d,e,f}
此设置适用于实际的考试应用程序,并将其标记为微不足道。
现在我有一个报告要求,出于审计目的,我需要生成一个如下所示的表:
ID 1 2 ... 100
Bob a c ... b
Chris c d ....null
所以我花了半天时间阅读有关PIVOT功能的内容,而我却得不到它。
这必须是我读过的最难以理解的文件。
首先,它需要和汇总功能 - 我应该在这里汇总什么?
我认为这只是PIVOT功能最简单的用法,而且我无法在任何地方找到一个体面的例子。帮助!
答案 0 :(得分: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>
如您所见,必须有聚合函数(聚合列)。 因此,表中的答案列必须是整数(十进制等),而不是char(1)。
编辑:MIN()和MAX()适用于char()数据类型。
你的桌子可以是这样的:
Create Table ExamAnswers
(
StudentID varchar(12) NOT NULL,
QuestionID int NOT NULL,
Answer int
)
使用PIVOT的SELECT语句将提供您需要的结果:
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
答案 1 :(得分: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值。