横表转换竖表:
CREATE table score ( username varchar(10) , chinese int , math int , physics int ); INSERT into score(username , chinese , math , physics) values(‘Kay‘,74,83,93); INSERT into score(username , chinese , math , physics) values(‘Jim‘,75,84,94); INSERT into score(username , chinese , math , physics) values(‘Lily‘,86,49,91); COMMIT; SELECT * FROM score;
横表转换成竖表关键在于如何把一条记录转换成多条记录,三个分数字段对应三条记录,可以采用一个只有三条记录中间表和score表做笛卡尔积把一条记录copy成三条记录
WITH T AS ( SELECT ‘chinese‘ course FROM dual UNION ALL SELECT ‘math‘ course FROM dual UNION ALL SELECT ‘physics‘ course FROM dual ) SELECT username,course,decode(course,‘chinese‘,chinese,‘math‘,math,‘physics‘,physics) FROM score ,T ORDER BY username ,course;
本文出自 “脚踏实地,仰望星空” 博客,请务必保留此出处http://xubcing.blog.51cto.com/3502962/1609478
原文地址:http://xubcing.blog.51cto.com/3502962/1609478