如何在oracle中合并一组记录?

时间:2016-02-03 10:29:42

标签: sql oracle group-by

考虑下表,

Name    | Subject_1    | Marks_1    | Subject_2    | Marks_2    |
Tom     | Maths        | 90         |              |            |
Tom     |              |            | Science      | 50         | 
Jon     |              |            | Science      | 70         |
Jon     | Maths        | 60         |              |            |

如何获得以下结果

Name    | Subject_1    | Marks_1    | Subject_2    | Marks_2    |
Tom     | Maths        | 90         | Science      | 50         |
Jon     | Maths        | 60         | Science      | 70         | 

尝试了GROUP BY的形式,但没有得到正确的结果,数学将始终属于主题_1和SUbject_2下的科学。

2 个答案:

答案 0 :(得分:2)

使用:

  • MAX
  • GROUP BY
SQL> SELECT NAME,
  2    MAX(subject_1) subject_1,
  3    MAX(marks_1) marks_1,
  4    MAX(subject_2) subject_2,
  5    MAX(marks_2) marks_2
  6  FROM t
  7  GROUP BY name;

NAME SUBJECT_1    MARKS_1 SUBJECT_2    MARKS_2
---- --------- ---------- --------- ----------
Jon  Maths             60 Science           70
Tom  Maths             90 Science           50

SQL>

另外,您需要考虑表格设计。您只能有3列name, subject, marks

如果您希望在同一个表格中包含单独的列,那么您应该将它们作为每个学生的单行。当您为学生提供新主题时,更新该学生的行,而不是添加新行。

答案 1 :(得分:0)

试试这个:

select maths.name,maths.subject_1,maths.marks_1,sci.subject_1,sci.marks_2 
from mytable maths,(select * from mytable where subject_2 is not null) sci 
where maths.name=sci.name
and maths.subject_1 is not null;