0

我正在尝试将一些数据分组并将一列分成几列。以下是我正在使用的表类型,尽管这些列中的每一列都来自通过每个表上的 ID 连接的各个表:

ParticipantId       QuestionText            QuestionAnswer
1               What is your gender?                2
2               What is your gender?                1
3               What is your gender?                1
4               What is your gender?                2
5               What is your gender?                1
1               What is your age?                   28
2               What is your age?                   NULL
3               What is your age?                   55
4               What is your age?                   63


And this is what I want to achieve:  


ParticipantId      Question1Answer    Question2Answer    Question3Answer        
        1               2               28                  3
        2               1               NULL                4

我想这是一件相当困难的事情吗?因为问卷包含大约 100 个问题。
如果不输入每个 questionID,我认为使用 case 是不合适的。我正在使用 SQL Server 2008。以下是我正在使用的一些表结构。我相信有比打字更清晰的方法。

QuestionnaireQuestion 表包含序列的 QuestionNumber,并通过 questionID(即 Question 表 PID)连接到 Question 表。问题表包含 QuestionText 并使用包含答案字段的 QuestionID 链接到 Answer 表。然后答案表通过一个名为 QuestionnaireInstance 的链接表,该链接表最终链接到包含 ParticipantID 的 PaperQuestionnaire 表。

这可能并没有使它更清楚,只是让我知道任何其他可能会使它更清楚的事情。

4

2 回答 2

1

如果您不想每次都输入所有问题文本,您可以随时使用:

;with sample_data as
(
SELECT
ParticipantId
,QuestionText
,QuestionAnswer
,row_number() OVER (PARTITION BY PARTICIPANTID ORDER BY (SELECT NULL)) AS rn
FROM yourdatatable
)
SELECT
PARTICIPANTID
,MAX(CASE WHEN rn = 1 THEN questionanswer END) AS Q1
,MAX(CASE WHEN rn = 2 THEN questionanswer END) AS Q2
,MAX(CASE WHEN rn = 3 THEN questionanswer END) AS Q3
,MAX(CASE WHEN rn = 4 THEN questionanswer END) AS Q4
FROM sample_data
GROUP BY ParticipantId

尽管在您的情况下考虑动态旋转可能会更好,但这取决于您最终希望获得多少列

于 2013-06-03T13:07:39.697 回答
0

如果您的表中列组合 ParticipantId 和 QuestionText 具有唯一性,那么您也可以使用以下查询来激活所需的输出 -

SELECT Participantid,
       MAX(CASE
             WHEN Questiontext = 'What is your gender?' THEN
              Questionanswer
             ELSE
              NULL
           END) AS Question1answer,
       MAX(CASE
             WHEN Questiontext = 'What is your age?' THEN
              Questionanswer
             ELSE
              NULL
           END) AS Question2answer,
       MAX(CASE
             WHEN Questiontext = '...your third question...' THEN
              Questionanswer
             ELSE
              NULL
           END) AS Question3answer,
       .. 
       ..
  FROM Your_Table_Name
 GROUP BY Participantid
于 2013-06-03T12:21:10.390 回答