我有一个表输出如下:
class | student | week | eng | maths | science
1 | stu1 | 1 | 67 | 78 | 89
1 | stu2 | 1 | 78 | 88 | 90
1 | stu3 | 1 | 45 | 34 | 45
1 | stu1 | 2 | 67 | 45 | 34
我需要最终输出:
class | student | sub | week1 | week2
1 | stu1 | eng | 67 | 67
1 | stu1 | maths | 78 | 45
1 | stu1 | science | 89 | 34
1 | stu2 | eng | 78 | 89
1 | stu2 | maths | 88 | 90
1 | stu2 | science | 90 | 89
1 | stu3 | eng | 45 |
1 | stu3 | maths | 34 |
1 | stu3 | science | 45 |
在表中,只有一部分,行被转换为列,列被转换为行。
我正在使用oracle 10g。
这是我对第一张表的查询。
select class, student,
to_char(dt,'WW') as week,
sum(case when sm.sub='eng' then 'eng' end) as eng,
sum(case when sm.sub='maths' then 'maths' end) as maths,
sum(case when sm.sub='science' then 'science' end) as science
from studentList sl left join studentMarks sm
on sl.stId=sm.stId
group by class, student, to_char(dt,'WW')
order by class, student;
答案 0 :(得分:0)
使用PIVOT / UNPIVOT运算符。请在这里找到一篇好文章: https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx