如何在oracle sql中将多行导入单行数据?

时间:2016-07-05 09:28:11

标签: oracle

假设在我们的源表中我们有以下数据:

Student Name    Subject Name        Marks
Sam             Maths                100
Tom             Maths                 80
Sam             Physical Science      80
John            Maths                 75
Sam             Life Science          70
John            Life Science         100
John            Physical Science      85
Tom             Life Science         100
Tom             Physical Science      85

我们希望将目标表加载为:

Student Name    Maths   Life Science    Physical Science
Sam              100      70              80
John              75     100              85
Tom               80     100              85

1 个答案:

答案 0 :(得分:0)

使用PIVOT运算符:

SELECT *
FROM   source
PIVOT ( MAX( marks ) FOR subject_name IN (
  'Maths'            AS Maths,
  'Life Science'     AS Life_Science,
  'Physical Science' AS Physical_Science
) );

<强>输出

STUDENT_NAME MATHS LIFE_SCIENCE PHYSICAL_SCIENCE
------------ ----- ------------ ----------------
Sam            100           70               80
John            75          100               85
Tom             80          100               85