2013-08-28 10 views
5

użyłem następujące zapytanie:Albo agregat funkcja lub klauzula 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 

Ale pojawia się następujący błąd:

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.

Odpowiedz

6

trzeba dodać do GROUP BY do zapytania:

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 wymaga kolumn na swojej liście SELECT, które nie są w funkcji agregacji b e zawarte w GROUP BY. Ponieważ próbujesz zwrócić wartość Patients.LastName podczas agregowania danych, musisz uwzględnić tę kolumnę w grupie według.

+0

Dzięki temu działało idealnie. Nie mogę uwierzyć, że przegapiłem coś tak prostego. – user2726146