分组并分成不同的列

时间:2013-06-03 11:53:35

标签: sql sql-server-2008

我正在尝试对一些数据进行分组,并将一列分成几列。以下是我正在使用的那种表,尽管这些列中的每一列都来自通过每个表上的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个问题。
如果不输入每个问题ID,我认为用例不合适。我正在使用SQL Server 2008.以下是我正在使用的一些表结构。我确信有一种比输入它更清晰的方式。

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

这可能没有让它更清楚,只要让我知道其他任何可能清除它的东西。

2 个答案:

答案 0 :(得分: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

虽然在您的情况下考虑dynamic pivoting可能会更好,但取决于您最终想要最终的列数

答案 1 :(得分:0)

如果您在列表组合ParticipantId和问题文本中具有唯一性,那么您也可以使用以下查询来获取所需的输出 -

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