假設有張學生成績表(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;