简体   繁体   English

如何从特定表中获取T-SQL中的平均值并将其结果与其他表连接?

[英]How to get average of values in T-SQL from specific table and join it's result with other one?

So basically, I have two tables: 所以基本上,我有两个表:

  • STUDENT {IdStudent Int (PK), IndexNr Varchar(10), Year Int, Name Varchar(32), Surname Varchar(64)} 学生{IdStudent Int(PK),IndexNr Varchar(10),Year Int,Name Varchar(32),Surname Varchar(64)}
  • MARK {IdMark Int (PK), IdStudent Int (FK), Value Int, Subject Varchar(32)} MARK {IdMark Int(PK),IdStudent Int(FK),Value Int,Subject Varchar(32)}

and as a first part of this exercise I need to run over them and grab all students from specific year (let's 2) and write out their average mark separately for each one of them. 作为本练习的第一部分,我需要让他们跑过去,抓住特定年份的所有学生(让我们为2),并分别为每个学生写下他们的平均成绩。

I wanted to do this through cursor but I'm having troubles with it. 我想通过游标执行此操作,但遇到了麻烦。 Mainly because I can't properly select these average marks using inner join. 主要是因为我无法使用内部联接正确选择这些平均分数。

For example I would like to return IndexNr and AverageMark. 例如,我想返回IndexNr和AverageMark。

You can do it by joining the tables and then use group by each student: 您可以通过加入表格来做到这一点,然后group by每个学生使用group by

select 
  s.idstudent, s.name, s.surname
  avg(m.Value) AverageMark
from student s inner join mark m
on m.idstudent = s.idstudent
where s.year = 2019
group by s.idstudent, s.name, s.surname

but shouldn't the table mark also contain a year column? 但是表格mark是否也不应包含year列?

I think GROUP BY is what you're looking for: https://www.w3schools.com/sql/sql_groupby.asp 我认为GROUP BY是您要寻找的: https : //www.w3schools.com/sql/sql_groupby.asp

SELECT 
    s.Name
    ,s.Year
    ,AVG(m.Value) as Mean        
FROM Student s
JOIN Mark m ON m.IdStudent = s.IdStudent
GROUP BY
    s.Name
    ,s.Year

If you want the average over all students, then you want one row. 如果要获得所有学生的平均数,则需要一行。 Don't use group by . 不要使用group by

You also need a where for the year condition: 您还需要一个whereyear的条件:

SELECT AVG(s.Value) as Mean
FROM student s
WHERE s.year = ?  -- whatever year you want

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM