横表转换竖表:
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;
时间: 2024-12-21 04:00:18