2

My table has the following columns:

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

Now i need data in this format:

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   

As you can see i want to display the columns as rows

Thanks

4

1 回答 1

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
于 2012-05-05T20:25:33.437 回答