SQL查询学生标记SQL Server中的功能

问题描述

有3张桌子@H_404_1@

  1. 学生(student_id,st_name)
  2. 主题(subject_id,sub_name)
  3. 标记(st_id,sub_id,得分)

编写SQL查询显示学生姓名,学生平均分数,学生获得的最高分,学生在其中获得最高分的科目名称。@H_404_1@

下面是我写的代码@H_404_1@

我遇到了错误-选择列表中的'students.name'和'subjects.name'列无效,因为它既不包含在聚合函数中也不包含在GROUP BY子句中。@H_404_1@

waitpid

解决方法

尝试

select students.name as Students_Name,avg(Score) as Average,max(Score) as Maximum,subjects.name as Max_Subject_name  
from marks 
INNER join students 
    on students.student_id=marks.st_id
INNER join subjects 
    on subjects.subject_id=marks.st_id
GROUP BY students.name,subjects.name
order by students.name,subjects.name;

或者如果您要查询:

select students.name as Students_Name,x.Average,x.Maximum,subjects.name as Max_Subject_name  
from marks 
join students on students.student_id=marks.st_id
join subjects on subjects.subject_id=marks.st_id
join
(
select st_id,avg(score) as Average,max(score) as Maximum from  marks group by st_id
) as x  on x.st_id=marks.st_id
order by students.name,subjects.name;
,

尝试一下

;with cte as
(
select students.st_name as Students_Name,students.student_id,RANK() over(partition by students.student_id  order by marks.score desc) as seq,subjects.sub_name as Max_Subject_name,Marks.Score
from marks 
INNER join students 
    on students.student_id=marks.st_id
INNER join subjects 
    on subjects.subject_id=marks.sub_id
)
select 
Students_Name,student_id,Max_Subject_name,Score,(select avg(score) from cte b where b.student_id=a.student_id) as average
from cte a
where seq=1