要么是集合函数,要么是GROUP BY子句。

问题描述 投票:5回答:1

我使用了下面的查询。

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.

sql sql-server join average
1个回答
10
投票

你需要添加一个 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 列表中不在集合函数中的内容,可以被包含在 GROUP BY. 由于你想返回的是 Patients.LastName 当你汇总数据时,你必须将该列包含在一个组中。

© www.soinside.com 2019 - 2024. All rights reserved.