在Oracle 11gR2中转置整个表(使用Pivot)

时间:2014-07-09 17:20:03

标签: sql oracle oracle11g pivot-table

我目前正在使用Oracle 11gR2并尝试使用Pivot转置整个表,但我遇到了一些问题。


学生表:

Student_id, math_grade, english_grade,  history_grade,  science_grade
1           A           B               C+               C-
2           B           B+              A-               B-
3           C           C               C                D
4           A+          A               A-               B+

期望的结果:

Student_id      1       2       3       4   
Math_grade      A       B       C       A+
English_grade   B       B+      C       A
History_grade   C+      A-      C       A-
Science_grade   C-      B-      D       B+

查询:

Select * 
From (
Select student_id, math_grade, english_grade, history_grade, science_grade
From student_table
Where student_id in (1,2,3,4); )
Pivot ( min(math_grade) as mathgrade, min(english_grade) as englishgrade, min(history_grade) as historygrade, min(science_grade) as sciencegrade
For student_id in (1 as Student1, 2 as Student2, 3 as Student3, 4 as student4) );

输出:

我以某种方式将所有数据转换为一个长行

Student1_mathgrade, student1_englishgrade,……student4_historygrade, student4_sciencegrade
A                   B                       A-                     B+

关于如何获得理想结果的任何建议?

2 个答案:

答案 0 :(得分:3)

这与@WalterM提供的答案基本相同,但我使用UNPIVOT代替工会。

select * from student_table
unpivot(grade for subject in (math_grade, english_grade, history_grade, science_grade))
pivot(min(grade) for student_id in (1, 2, 3, 4));

答案 1 :(得分:0)

由于PIVOT子句通常用于转置聚合数据,因此在使用PIVOT之前将列转换为行是有帮助的。您可以尝试以下方法:

SELECT *
  FROM (
   SELECT student_id, 'MATH' "CLASS", math_grade "GRADE"
     FROM test
   UNION
   SELECT student_id, 'ENGLISH' "CLASS", english_grade "GRADE"
     FROM test
   UNION
   SELECT student_id, 'HISTORY' "CLASS", history_grade "GRADE"
     FROM test
   UNION
   SELECT student_id, 'SCIENCE' "CLASS", science_grade "GRADE"
     FROM test
  )
  PIVOT (
    MIN(grade)
    FOR student_id IN
    (1 student_1, 2 student_2, 3 student_3, 4 student_4)
  );

您可能需要修改列名和行顺序,但可以使用包装器SELECT语句来完成。