假设有张学生成绩表(zb)如下:
我现在我需要得到如下的数据
用DECODE或者CASE来实现相互转化:
select name 姓名, max(case subject when ‘语文‘ then result else 0 end) 语文, max(case subject when ‘数学‘ then result else 0 end) 数学, max(case subject when ‘物理‘ then result else 0 end) 物理 from zb group by name; ---------------------------------------------------------------------- select name 姓名, max(decode(subject, ‘语文‘, result, 0)) 语文, max(decode(subject, ‘数学‘, result, 0)) 数学, max(decode(subject, ‘物理‘, result, 0)) 物理 from zb group by name;
这两个语句都可以实现我们的需求。
反之:
select * from (select 姓名 as Name, ‘语文‘ as Subject, 语文 as Result from hb union all select 姓名 as Name, ‘数学‘ as Subject, 数学 as Result from hb union all select 姓名 as Name, ‘物理‘ as Subject, 物理 as Result from hb) t order by name, case Subject when ‘语文‘ then 1 when ‘数学‘ then 2 when ‘物理‘ then 3 end;
此时我们还可以增加总分,平均分的字段:
select * from (select 姓名 as Name, ‘语文‘ as Subject, 语文 as Result from hb union all select 姓名 as Name, ‘数学‘ as Subject, 数学 as Result from hb union all select 姓名 as Name, ‘物理‘ as Subject, 物理 as Result from hb) t order by name, case Subject when ‘语文‘ then 1 when ‘数学‘ then 2 when ‘物理‘ then 3 end;