我正在尝试编写一个创建数据透视表的sql语句。
数据是一份调查回复列表,由一个涉及表格响应者,回复和答案的连接查询构成。答案表的结构如下:
______________________________________________________________
|AnswerID|ResponseID|QuestionID|AnswerComment |
| 1 | 1 | 1 |This is answer 1 |
| 2 | 1 | 2 |This is answer 2 |
| 3 | 1 | 3 |This is answer 3 |
| 4 | 2 | 1 |Answer 1 Respondent 2 |
| 5 | 2 | 3 |Resp 2, No Q.2 |
| 6 | 3 | 2 |I answered Q.2 only |
|____________________________________________________________|
受访者看起来像:
______________________________________________________________
|RespondentID|GivenName|Surname|age, gender, blah blah |
|____________________________________________________________|
响应:
______________________________________________________________
|ResponseID|ResponseDate|RespondentID|Attachment |
|____________________________________________________________|
和问题:
_____________________________________________________
|QuestionID|QuestionNumber|QuestionText| |
|___________________________________________________|
我希望我的输出形式为:
________________________________________________________________________________________
|RespondentInfo|ResponseDate|1 |2 |3 |
|Respondent 1 |15/10/2012 |This is answer 1 |This is answer 2 |This is answer 3|
|Respondent 2 |17/10/2012 |Answer 1 Respondent 2 | |Resp 2, No Q.2 |
|Respondent 3 |19/10/2012 | |I answered Q.2 only| |
|______________________________________________________________________________________|
我希望每位受访者在相应列中得到一行答案。我创建的查询 - 虽然它将答案转移到正确的列 - 为每个答案提供了一个新行,所有空白列都有空值。
我的sql:
SELECT Respondent, ResponseDate,
[1], [2], [3]
FROM (
SELECT Respondent.Surname + ', ' + FirstName as RespondentInfo,
Response.ResponseDate,
isnull(Answer.AnswerComment, '') as Answer,
Qustion.QuestionNumber
FROM Answer INNER JOIN
Question ON Answer.QuestionID = Question.QuestionID INNER JOIN
Response ON Answer.ResponseID = Response.ResponseID INNER JOIN
Respondent ON Response.RespondentID = Respondent.RespondentID
) as ResponseQuery
PIVOT (
max(Answer)
FOR ResponseQuery.QuestionNumber in ([1], [2], [3])
) AS OutputTable
我认为问题是因为我没有使用聚合函数,所以默认为max()。任何人都可以指出我正确的方向。
如果我的问题太冗长,请道歉。
答案 0 :(得分:0)
问题是来源,而不是支点。
很难说没有看到其他表,而是使用示例表
select ResponseID, [1],[2],[3] from
(select ResponseID, AnswerComment, QuestionID from yourtable) s
PIVOT (max(AnswerComment) FOR QuestionID in ([1], [2], [3]) ) AS OutputTable
以你所追求的形式产生输出。
如果您无法弄清楚如何调整源以提供您想要的数据,您可以通过添加类似的内容来加入数据后...
inner join Response on OutputTable.ResponseID = Response.ResponseID
在上面的支点后给出
select Response.ResponseDate, [1],[2],[3] from
(select ResponseID, AnswerComment, QuestionID from yourtable) s
PIVOT (max(AnswerComment) FOR QuestionID in ([1], [2], [3]) ) AS OutputTable
inner join Response on OutputTable.ResponseID = Response.ResponseID
等...