3.数据库"列转行"又是怎样一种情况?
数据库"列转行"是数据库"行转列"的反过程,即:将上实例中的②表中数据的显示形式,转换为①表中数据的显示形式。 4.如何实现"行转列" or "列转行"
实现"行转列" or "列转行"有两种转换方法:静态转换方法、动态转换方法。采用哪一种方式,视情况而定。
以上例说明:A.当课程中的内容是固定的几项,例如课程只有语文、数学、物理,可以使用静态转换来实现,当然也可以使用动态转换方式。
B.如果课程的种类是动态变换的,这时我们只能使用动态转换方式了。
--创建学生成绩表T_StudentScore
create table T_StudentScore(PK_ID int ,Name varchar(10) , Course varchar(10) , Score int)
--更改PK_ID 的列属性,选择”是标识“,标识增量为1,也就是PK_ID 字段的数据是自增长的
--向学生成绩表添加几条成绩信息
insert into T_StudentScore values('木子' , '语文' , 74)
insert into T_StudentScore values('木子' , '数学' , 83)
insert into T_StudentScore values('木子' , '物理' , 93)
insert into T_StudentScore values('山石' , '语文' , 74)
insert into T_StudentScore values('山石' , '数学' , 84)
insert into T_StudentScore values('山石' , '物理' , 94)
3.利用一般查询方式:课程为字段 3.1 简单查询出"学生成绩表"所有信息
使用SQL语句
--查询学生成绩表的信息
select * from T_StudentScore
结果显示为: 3.2
查询出"学生成绩表"所有信息,列名显示为中文<别名>
使用SQL语句
--查询学生成绩表的信息
select PK_ID as '编号',Name as '姓名',Course as '课程',Score as '成绩' from T_StudentScore
结果显示为: 4.行转列 静态方式
4.1 SQL 2000静态转换方式
--行转列 静态方法
select Name as 姓名 ,
max(case Course when '语文' then Score else 0 end) 语文,
max(case Course when '数学' then Score else 0 end) 数学,
max(case Course when '物理' then Score else 0 end) 物理
from T_StudentScore
group by Name
4.2 另一种静态转换方式
--行转列,静态转换
select distinct c.[Name] as 姓名,
(select Score from T_StudentScore where Name=c.[Name] and Course='语文')as 语文,
(select Score from T_StudentScore where Name=c.[Name] and Course='数学')as 数学,
(select Score from T_StudentScore where Name=c.[Name] and Course='物理')as 物理
from T_StudentScore c