SQL Server 2008:使用 AVG() 和内部联接

Dar*_*ren 4 sql-server-2008 query

这是我到目前为止所拥有的。我知道这有效,但我需要获得 和 的平均值,pulsedepressionlevel不是为每一行返回实际值:

SELECT
  Patients.LastName
  , PatientVisit.Pulse AS [avg Pulse]
  , PatientVisit.DepressionLevel AS [avg Deplevel]
FROM Patients
    INNER JOIN PatientVisit on Patients.PatientKey = PatientVisit.PatientKey
ORDER BY
  Patients.LastName
Run Code Online (Sandbox Code Playgroud)

Rob*_*ley 6

SELECT Patients.LastName, 
AVG(PatientVisit.Pulse) as "avg Pulse", 
AVG(PatientVisit.DepressionLevel) as "avg Deplevel" 
from Patients 
inner join 
PatientVisit 
on Patients.PatientKey = PatientVisit.PatientKey 
GROUP BY Patients.PatientKey, Patients.LastName
order by Patients.LastName;
Run Code Online (Sandbox Code Playgroud)

按 PatientKey 分组也很重要,因此您没有 Smiths 和 Nguyens 的单一记录。它还允许额外的优化,因为它(应该)被标记为唯一的(作为主键)。