聚合函数或GROUP BY子句

时间:2021-09-05 22:49:30

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.

消息8120,级别16,状态1,行1列'Patientss.LastName'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

1 个解决方案

#1


8  

You need to add a GROUP BY to your query:

您需要在查询中添加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 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.

SQL Server要求SELECT列表中不在聚合函数中的任何列都包含在GROUP BY中。由于您在聚合数据时尝试返回Patients.LastName,因此必须在组中包含该列。

#1


8  

You need to add a GROUP BY to your query:

您需要在查询中添加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 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.

SQL Server要求SELECT列表中不在聚合函数中的任何列都包含在GROUP BY中。由于您在聚合数据时尝试返回Patients.LastName,因此必须在组中包含该列。