假设有张学生成绩表(zb)以下:post
我如今我须要获得以下的数据spa
用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;
这两个语句均可以实现咱们的需求。code
反之:blog
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;
此时咱们还能够增长总分,平均分的字段:ip
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;