横表结构
create table Table_B
(
姓名 varchar(20),
语文 int,
数学 int,
英语 int
)
insert into Table_B(姓名,语文,数学,英语) values('张三',60,70,80)
insert into Table_B(姓名,语文,数学,英语) values('李四',90,100,0)
![](https://img2018.cnblogs.com/blog/412541/201905/412541-20190527111722077-201960293.jpg)
纵表结构
create table Table_A
(
姓名 varchar(20),
课程 varchar(20),
成绩 int
)
insert into Table_A(姓名,课程,成绩) values('张三','语文',60)
insert into Table_A(姓名,课程,成绩) values('张三','数学',70)
insert into Table_A(姓名,课程,成绩) values('张三','英语',80)
insert into Table_A(姓名,课程,成绩) values('李四','语文',90)
insert into Table_A(姓名,课程,成绩) values('李四','数学',100)
![](https://img2018.cnblogs.com/blog/412541/201905/412541-20190527111737346-868376534.jpg)
横表转纵表
select 姓名,'语文' as 课程,语文 as 成绩 from Table_B union all
select 姓名,'数学' as 课程,数学 as 成绩 from Table_B union all
select 姓名,'英语' as 课程,英语 as 成绩 from Table_B
order by 姓名,课程 desc;
纵表转横表
select 姓名,
sum (case 课程 when '语文' then 成绩 else 0 end) as 语文,
sum (case 课程 when '数学' then 成绩 else 0 end) as 数学,
sum (case 课程 when '英语' then 成绩 else 0 end) as 英语
from Table_A
group by 姓名;