枢轴功能

时间:2018-12-17 11:13:59

标签: sql sql-server unpivot

当前表格如下

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

但是我需要这样的表:

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

直到列出register_number 1的所有主题为止,我需要跟进reg_number-2直到在该特定表中找到记录数

我非常确定要使用[pivot]函数,但不知道如何基于行中的特定[register_number]实体添加特定行的多列

预先感谢

2 个答案:

答案 0 :(得分:4)

您想要unpivot而不是pivot

select t.register_number, tt.subjects, tt.marks
from table t cross apply
     ( values ('maths', maths),
              ('computer', computer),
               . . . ,
              ('total', total)
     ) tt (subjects, marks);

答案 1 :(得分:1)

我认为您应该使用枢纽 试试这个查询

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