Either an aggregate function or the GROUP BY claus

2019-06-20 16:18发布

I used the following query:

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

But I get the following error:

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.

1条回答
一纸荒年 Trace。
2楼-- · 2019-06-20 16:42

You need to add a GROUP BY to your query:

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 requires any columns in your SELECT list that are not in an aggregate function be included in a GROUP BY. Since you are trying to return the Patients.LastName while you are aggregating the data you must include that column in a group by.

查看更多
登录 后发表回答