art1:列转行。需求:
示例给出这么一张表:
表定义如下:
create table TEST_TB_GRADE
( ID NUMBER(10) not null,
USER_NAME VARCHAR2(20 CHAR),
COURSE VARCHAR2(20 CHAR),
SCORE FLOAT )
要求转换成为:
下面给出一个可行的PL/SQL语句:
select
t.user_name as 姓名,
sum(decode(t.course, '语文', score,null)) as 语文,
sum(decode(t.course, '数学', score,null)) as 数学,
sum(decode(t.course, '英语', score,null)) as 英语
from test_tb_grade t
group by t.user_name
order by t.user_name
实现效果如下图需求所示。
Part2:行转列。需求:
示例给出这样一张表
表结构如下:
create table TEST_TB_GRADE2
( ID NUMBER(10) not null,
USER_NAME VARCHAR2(20 CHAR),
CN_SCORE FLOAT,
MATH_SCORE FLOAT,
EN_SCORE FLOAT )
需要转换成如下形式:
下面给出一个可执行的PL/SQL语句:
select
user_name,
'语文'as COURSE ,
CN_SCORE as SCORE
from test_tb_grade2
union all
select
user_name,
'数学'as COURSE,
MATH_SCORE as SCORE
from test_tb_grade2
union all
select user_name,
'英语'as COURSE,
EN_SCORE as SCORE
from test_tb_grade2
order by user_name,COURSE
实现效果如下图需求所示。