【问题标题】:Update on SQL Server using AVG and MAX使用 AVG 和 MAX 更新 SQL Server
【发布时间】:2020-07-11 04:00:25
【问题描述】:

谁能帮帮我?

我有两个表ResultsStudents 显示在这里:

StudentID   CourseID   Year     Semester    Mark 
------------------------------------------------
   S001       DS01     2017        1        3 
   S001       DS01     2017        2        6   
   S001       AI01     2017        1        4.5 
   S001       AI01     2017        2        6 
   S001       CN01     2017        3        5 
   S002       DS01     2016        1        4.5 
   S002       DS01     2017        1        7 
   S002       CN01     2016        3       10 
   S002       DSA1     2016        3        9 

StudentID   LastName    FirstName   Sex     DateOfBirth     PlaceOfBirth    DeptID  Scholarship     AverageScore
S001    Lê  Kim Lan     F   23/02/1990  Hà nội  IS  130000  
S002    Trần Minh Chánh     M   24/12/1992  Bình Định   NC  150000  

(AverageScore 现在为空)

我想用课程 ID 更新 - 你能帮我吗?

这是我的代码:

update Students
set AverageScore = (select avg(max(Mark).CourseID) 
                    from Results 
                    where Results.StudentID = Students.StudentID)

【问题讨论】:

  • 预期输出是什么?
  • 请详细说明您的问题。正如我们所见,同一个学生有不同的课程,同一个课程有多个分数。但是学生表中只有一个平均字段。您想为特定学生获取每个课程的最大值并将它们平均并将其保存在学生表中吗?例如:5001 => (6 (DS01 最大值) + 6 (AI01 最大值) + 5 (CN01)) / 3 = 17/3 = 5.67

标签: sql-server max average


【解决方案1】:

您可以使用以下子查询:

update Students set AverageScore = (select avg(marks) from (
     Select max(mark) as marks
     from Results 
     where Results.StudentID = Students.StudentID  group by Results.courseid  ) )

【讨论】:

    【解决方案2】:

    你可以试试这个:

    ;WITH aa AS(
     SELECT resultid,CourseID,MAX(Mark) mark FROM result GROUP BY resultid,CourseID )
    UPDATE dbo.student SET AverageScore=(select AVG(mark) from aa WHERE aa.resultID=student.resultID)
    select * from dbo.student
    

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 2019-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多