--■■■分析関数を使う方法■■■
select distinct 試験名,名前,
Last_Value(科目) over(partition by 試験名,名前,Replace(科目,'(追試)')
order by 点数,instr(科目,'(追試)') desc
Rows between Unbounded Preceding and Unbounded Following) as 科目,
max(点数) over(partition by 試験名,名前,Replace(科目,'(追試)')) as 点数
from 試験
order by 名前,試験名 desc,科目;
--■■■existsを使う方法■■■
select 試験名,名前,科目,点数
from 試験 a
where instr(科目,'(追試)') = 0
and not exists(select 1 from 試験 b
where b.試験名 = a.試験名
and b.名前 = a.名前
and instr(b.科目,'(追試)') > 0
and replace(b.科目,'(追試)') = a.科目
and b.点数 > a.点数)
or instr(科目,'(追試)') > 0
and not exists(select 1 from 試験 b
where b.試験名 = a.試験名
and b.名前 = a.名前
and instr(b.科目,'(追試)') = 0
and replace(a.科目,'(追試)') = b.科目
and b.点数 >= a.点数)
order by 名前,試験名 desc,科目;