Search code examples
sqlsql-serverunpivot

Pivot functionality


The current table looks like this

ID|reg_ num|student_name|maths|computer |language|total
--+--------+------------+-----+---------+--------+------
1 |001     |james       |50   |50       |50      |150
2 |002     |john        |60   |50       |50      |160
3 |003     |alex        |50   |70       |50      |170
4 |004     |david       |50   |50       |80      |180

But i need the table in such a way that:

register_ number|subjects |marks
----------------+---------+---
              1 |maths    |50 (again)
              1 |languages|40 ....

Till all the subjects of the register_number 1 is listed out, and I need a follow up by reg_number - 2 till the number of records are found in that particular table

I am pretty sure that the [ pivot ] function to be used but don't know how to add multiple column of a particular row based on a particular [register_number] entity in the row

Thanks in advance


Solution

  • I think you should use unpivot try this query

    select u.register_number, u.subject, u.marks
    from studentmarks s
    unpivot
    (
      marks
      for subject in (Maths,computer,...)
    ) U;