如何解决SQL查询学生标记SQL Server中的功能
有3张桌子
- 学生(student_id,st_name)
- 主题(subject_id,sub_name)
- 标记(st_id,sub_id,得分)
编写SQL查询以显示学生姓名,学生平均分数,学生获得的最高分,学生在其中获得最高分的科目名称。
下面是我写的代码
我遇到了错误-选择列表中的'students.name'和'subjects.name'列无效,因为它既不包含在聚合函数中也不包含在GROUP BY子句中。
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。