在SQL中透视调查数据表,不使用PIVOT



我有一个名为Responses的表,其中包含使用以下结构的调查回复。

RespondentID    | QuestionID | Text
----------------+------------+--------------------
745000000144003 | 1          | 424847508003102140
745000000144003 | 2          | someone@example.com
745000000144003 | 3          | 10
745000000144003 | 4          | Long text
745000000137035 | 1          | 548470363003102141
745000000137035 | 2          | someone@me.com
745000000137035 | 3          | 9
745000000137035 | 4          | Long text

这是两个不同调查的数据。每个调查有4个问题(questionid),但最后一个(长文本)是可选的,所以一些回答只有3行数据。第一个问题(QuestionID "1")也可以作为调查回复的主键。

我正在尝试pivot数据,因此每个QuestionID都是它自己的列,因此每个调查响应只有一行。我使用的是Zoho Analytics,我认为它不支持PIVOT。

谢谢你的帮助!

你真的不需要PIVOT(你没有标记你的数据库,可能是MS SQL server):

Select RespondentId, 
Max(Case when QuestionId = 1 then [Text] end) Answer1,
Max(Case when QuestionId = 2 then [Text] end) Answer2,
Max(Case when QuestionId = 3 then [Text] end) Answer3,
Max(Case when QuestionId = 4 then [Text] end) Answer4
from mySurvey 
Group by RespondentId;

PS:这与网络无关。

如果我理解正确的话,你可以使用条件聚合的形式。

select
respondent_id,
max(case when QuestionId = 1 then max<text column> end) as Question1,
...
from
...
group by respondent_id

最新更新