Split Multiple Columns into Multiple Rows

前端 未结 3 1618
花落未央
花落未央 2021-01-04 07:26

I have a table with this structure.

UserID  | UserName  | AnswerToQuestion1 | AnswerToQuestion2 | AnswerToQuestion3
1       | John      | 1                 |         


        
3条回答
  •  情话喂你
    2021-01-04 08:03

    SELECT
       Y.UserID,
       Y.UserName,
       QuestionName = 'AnswerToQuestion' + X.Which,
       Response =
          CASE X.Which
          WHEN '1' THEN AnswerToQuestion1
          WHEN '2' THEN AnswerToQuestion2
          WHEN '3' THEN AnswerToQuestion3
          END
    FROM
       YourTable Y
       CROSS JOIN (SELECT '1' UNION ALL SELECT '2' UNION ALL SELECT '3') X (Which)
    

    This performs equally well to UNPIVOT (sometimes better) and works in SQL 2000 as well.

    I took advantage of the questions' similarity to create the QuestionName column, but of course this will work with varying question names.

    Note that if your list of questions is long or the question names are long, you might experiment with 2 columns in the X table, one for the question number and one for the question name. Or if you already have a table with the list of questions, then CROSS JOIN to that. If some questions are NULL then easiest is to put the above query in a CTE or derived table and then add WHERE Response IS NOT NULL.

提交回复
热议问题