1.学生编号 学生姓名 科别 成绩
01 张三 数学 87
01 张三 语文 66 输出如下结果 学生编号 学生姓名 数学 语文
02 李四 数学 90 01 张三 87 66
02 李四 语文 78 02 李四 90 78
2.student表 stuID,stuName
course表 stuID,courseName,courseMark 得出与指定学生'张三'选择相同课程的其他学生(一个学生可以选择多个课程)请大家指教这两个SQL语句该怎么写
01 张三 数学 87
01 张三 语文 66 输出如下结果 学生编号 学生姓名 数学 语文
02 李四 数学 90 01 张三 87 66
02 李四 语文 78 02 李四 90 78
2.student表 stuID,stuName
course表 stuID,courseName,courseMark 得出与指定学生'张三'选择相同课程的其他学生(一个学生可以选择多个课程)请大家指教这两个SQL语句该怎么写
max(case when course='语文' then 语文 else 0 end) as '语文',
max(case when course='数学' then 数学 else 0 end) as '数学'
from tb
)insert @stu
select 01 ,'张三', '数学', 87 union all
select 01 ,'张三', '语文', 66 union all
select 02 ,'李四', '数学', 90 union all
select 02 ,'李四', '语文' ,78 select 学生编号,学生姓名,
数学=max(case 科别 when '数学' then 成绩 end),
语文=max(case 科别 when '语文' then 成绩 end)
from @stu
group by 学生编号,学生姓名
select
[StuID],[数学],[语文]from tb a
pivot
(max([Score]) for [Course] in([数学],[语文]))b
select stuID,stuName
max(case when course='语文' then 语文 else 0 end) as '语文',
max(case when course='数学' then 数学 else 0 end) as '数学'
from tb
group by stuID,stuName
select 学生编号,学生姓名,
max(case when 科别='数学' then 成绩 else 0 end) as '数学',
max(case when 科别='语文' then 成绩 else 0 end) as '语文'
from student group by 学生编号,学生姓名
Student(S#,Sname,Sage,Ssex) 学生表
Course(C#,Cname,T#) 课程表
SC(S#,C#,score) 成绩表
Teacher(T#,Tname) 教师表 select S# from SC where C# in (select C# from SC where S#='1002')
group by S# having count(*)=(select count(*) from SC where S#='1002')
课程表设计得不合理,不符合第二范式,哪有课程表会设计个学生编号字段,得设个成绩表。
以上参考
1.
Create table #score(sid varchar(5),sname nvarchar(30),course nvarchar(100),score int)
Insert into #score(sid,sname,course,score)
select '01',N'张三',N'数学',87 union all
select '01',N'张三',N'语文',66 union all
select '02',N'李四',N'数学',90 union all
select '02',N'李四',N'语文',78select sid,sname
,MAX(case when course=N'数学' then score else 0 end) as [数学]
,MAX(case when course=N'语文' then score else 0 end) as [语文]
from #score
group by sid,snameSelect * FROM #score pivot( max(score) for course in ([数学],[语文])) as a