在 SQL 中透视 table 调查数据而不使用 PIVOT
Pivoting a table of survey data in SQL without PIVOT
我有一个名为 Responses 的 table,其中包含使用以下结构的调查回复。
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") 也可以作为调查回复的主键。
我正在尝试旋转数据,以便每个 QuestionID 都是它自己的列,并且每个调查响应都只有一行。我正在使用我认为不支持 PIVOT 的 Zoho Analytics。
感谢您的帮助!
你真的不需要 PIVOT(你没有标记你的数据库,可能是 MS SQL 服务器):
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
我有一个名为 Responses 的 table,其中包含使用以下结构的调查回复。
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") 也可以作为调查回复的主键。
我正在尝试旋转数据,以便每个 QuestionID 都是它自己的列,并且每个调查响应都只有一行。我正在使用我认为不支持 PIVOT 的 Zoho Analytics。
感谢您的帮助!
你真的不需要 PIVOT(你没有标记你的数据库,可能是 MS SQL 服务器):
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