Select语句将表的列转换为行

时间:2018-11-23 17:49:25

标签: sql

我有一个名为'tblQuestions'的以下SQL表:

    questionID    Question      Option1 Option2 Option3 Option4 
      1          Whats 1 + 1         1     2       3      4

我正在尝试为这些选项做一条选择语句,它将把行转换为以下格式:

 AnswerText AnswerValue
    1          1    
    2          2
    3          3
    4          4

因此,每个选项应单独作为一列,而应作为单独的行

很抱歉,如果表格的格式不正确,谢谢您的帮助!

1 个答案:

答案 0 :(得分:4)

我强烈建议您将数据库重组为以下内容:

tbl问题

PK = Question_ID

+-------------+--------------+
| Question_ID |   Question   |
+-------------+--------------+
|           1 | What is 1+1? |
|           2 | What is 2+2? |
|         ... | ...          |
+-------------+--------------+

tblOptions

PK = Question_ID + Option_ID

+-------------+-----------+--------------+
| Question_ID | Option_ID | Option_Value |
+-------------+-----------+--------------+
|           1 |         1 |            1 |
|           1 |         2 |            2 |
|           1 |         3 |            3 |
|           1 |         4 |            4 |
|           2 |         1 |            7 |
|           2 |         2 |            5 |
|           2 |         3 |            4 |
|         ... |       ... |          ... |
+-------------+-----------+--------------+

然后也许是一个答案表,其中包含每个问题的正确选项-

tblAnswers

PK = Question_ID

+-------------+-----------+
| Question_ID | Option_ID |
+-------------+-----------+
|           1 |         2 |
|           2 |         3 |
|         ... |       ... |
+-------------+-----------+