WHERE 子句中可能不会出现聚合(SQL Server 错误)

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

当我尝试这个查询时,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

我收到了这个错误:

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.

有人可以帮忙解决这个问题吗?


正确的语法应该是...

1
2
3
4
5
6
7
8
9
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%'