问个有点点挑战的问题!三张表玩交叉,有强悍的来吗?
问个有点点挑战的问题:
有三张表:
学生表:
ID 姓名
------------
1 张三
2 李四
课程表:
ID 课程
------------
1 数学
2 语文
3 英语
成绩表:
学生表的ID 课程表的ID 成绩
------------------------------
1 1 88
2 1 77
1 2 99
1 3 0
2 3 35
2 2 0
表好了,然后我想用交叉表这样显示:
(SQL语句实现)
姓名 数学 语文 英语
张三 88 99 0
李四 77 0 35
[解决办法]
--> 测试数据: #学生表if object_id('tempdb.dbo.#学生表') is not null drop table #学生表create table #学生表 (ID int,姓名 varchar(4))insert into #学生表select 1,'张三' union allselect 2,'李四'--> 测试数据: #课程表if object_id('tempdb.dbo.#课程表') is not null drop table #课程表create table #课程表 (ID int,课程 varchar(4))insert into #课程表select 1,'数学' union allselect 2,'语文' union allselect 3,'英语'--> 测试数据: #成绩表if object_id('tempdb.dbo.#成绩表') is not null drop table #成绩表create table #成绩表 (学生ID int,课程ID int,成绩 int)insert into #成绩表select 1,1,88 union allselect 2,1,77 union allselect 1,2,99 union allselect 1,3,0 union allselect 2,3,35 union allselect 2,2,0godeclare @sql varchar(8000)set @sql='select a.姓名'select @sql=@sql+',max(case when b.课程ID='+ltrim(ID)+' then b.成绩 else 0 end) ['+课程+']'from #课程表exec (@sql+' from #学生表 a join #成绩表 b on a.ID=b.学生ID group by a.姓名')godrop table #学生表,#课程表,#成绩表/*姓名 数学 语文 英语 ---- ----------- ----------- ----------- 李四 77 0 35张三 88 99 0*/
[解决办法]
create table xuesheng(id int,xingming nvarchar(20))insert into xueshengselect 1 , '张三'union select 2, '李四'create table kecheng (id int, mingcheng nvarchar(20))insert into kechengselect 1 , '数学'union select 2, '语文'union select 3, '英语'create table chengji(xueshengid int ,chengjiid int,chengji int)insert into chengji select 1 , 1 , 88 union select 2 , 1 , 77 union select 1 , 2 , 99 union select 1 , 3 , 0 union select 2 , 3 , 35 union select 2 , 2 , 0 create view chengjidanas select xingming,mingcheng,chengji fromxuesheng X,kecheng K,chengji Cwhere X.id=C.xueshengid and K.id=C.chengjiidselect xingming,[数学],[语文],[英语] from chengjidanpivot(max(chengji) for mingcheng in ([数学],[语文],[英语]) ) pvt