Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An aggregate may not appear in the WHERE clause( SQL Server Error )

Tags:

sql

sql-server

When I tried this query,

select  
    (A.StudentId),
     max(A.StudentFirstName),
     max(A.StudentLastName),
     max(A.StudentAddress),
     'Batch ' + max(C.BatchName),
     CAST(MAX(CAST(A.StudentStatus as INT)) AS BIT),
     max(B.StudentBatchId) 
from 
    tblStudentDetails A  
inner join 
    tblStudentBatchDetails B on A.StudentId = B.studentid 
inner join 
    tblBatch C on C.BatchId = B.batchid 
where 
    max(A.StudentFirstName) like 'A%'
group by 
    A.StudentId

I got this error:

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

Can someone help to recover this problem?

like image 887
K.Suthagar Avatar asked Dec 28 '25 13:12

K.Suthagar


1 Answers

The correct syntax would be...

select  (A.StudentId),max(A.StudentFirstName),
max(A.StudentLastName),max(A.StudentAddress),
'Batch ' + max(C.BatchName),CAST(MAX(CAST(A.StudentStatus as INT)) AS BIT),
max(B.StudentBatchId) 
from tblStudentDetails A  
inner join tblStudentBatchDetails B on A.StudentId=B.studentid 
inner join tblBatch C on C.BatchId=B.batchid 
group by A.StudentId
having max(A.StudentFirstName) like 'A%'
like image 136
Spock Avatar answered Dec 31 '25 04:12

Spock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!