2013-08-28 211 views
5

我用下面的查詢:聚合函數或GROUP BY子句

select Patients.LastName, 
    avg (PatientVisits.Pulse)as pulse, 
    avg (patientvisits.depressionlevel)as depressionLevel 
from Patients 
left join PatientVisits 
    on Patients.PatientKey=PatientVisits.PatientKey 

,但我得到了以下錯誤:

Msg 8120, Level 16, State 1, Line 1 Column 'Patients.LastName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

回答

6

你需要一個GROUP BY添加到您的查詢:

select Patients.LastName, 
    avg (PatientVisits.Pulse)as pulse, 
    avg (patientvisits.depressionlevel)as depressionLevel 
from Patients 
left join PatientVisits 
    on Patients.PatientKey=PatientVisits.PatientKey 
GROUP BY Patients.LastName 

SQL Server要求您的SELECT列表中的任何列不在聚合函數b中e包含在GROUP BY中。由於您在彙總數據時試圖返回Patients.LastName,因此您必須在該組中包含該列。

+0

非常感謝您的工作。我不能相信我錯過了那麼簡單的事情。 – user2726146

相關問題