SQL查询将列转换为行

时间:2012-05-05 20:22:30

标签: sql

我的表格包含以下列:

roll no | subject1 | subject2 | subject3 | subject4 | subject5 | subject6
   1    |    10    |    12    |    13    |    9     |    15    |    16
   2    |    12    |    14    |    10    |    16    |    19    |    13
   3    |    10    |    12    |    13    |    18    |    12    |    15
   4    |    14    |    12    |    13    |    7     |    11    |    17

现在我需要这种格式的数据:

Roll no | SubjectName | Marks
    1   |  subject1   |  10     
    1   |  subject2   |  12     
    1   |  subject3   |  13     
    1   |  subject4   |  9     
    1   |  subject5   |  15     
    1   |  subject6   |  16     
    2   |  subject1   |  12     
    2   |  subject2   |  14     
    2   |  subject3   |  10     
    2   |  subject4   |  16     
    2   |  subject5   |  19     
    2   |  subject6   |  13   
    3   |  subject1   |  10     
    3   |  subject2   |  12     
    3   |  subject3   |  13     
    3   |  subject4   |  18     
    3   |  subject5   |  12     
    3   |  subject6   |  15  
    4   |  subject1   |  14     
    4   |  subject2   |  12     
    4   |  subject3   |  13     
    4   |  subject4   |  7     
    4   |  subject5   |  11     
    4   |  subject6   |  17   

如您所见,我想将列显示为行

由于

1 个答案:

答案 0 :(得分:5)

如果您的数据库支持UNPIVOT,则可以使用它。

如果没有,您可以使用UNION ALL

SELECT roll_no, 'subject1' AS SubjectName, subject1 AS Marks FROM yourtable
UNION ALL
SELECT roll_no, 'subject2', subject2 FROM yourtable
UNION ALL
SELECT roll_no, 'subject3', subject3 FROM yourtable
UNION ALL
SELECT roll_no, 'subject4', subject4 FROM yourtable
UNION ALL
SELECT roll_no, 'subject5', subject5 FROM yourtable
UNION ALL
SELECT roll_no, 'subject6', subject6 FROM yourtable
UNION ALL
SELECT roll_no, 'subject7', subject7 FROM yourtable