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

时间:2016-04-02 15:23:39

标签: sql sql-server

当我尝试此查询时,

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

我收到了这个错误:

  

聚合可能不会出现在WHERE子句中,除非它在a中   包含在HAVING子句或选择列表中的子查询以及列   被聚合是一个外部参考。

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

1 个答案:

答案 0 :(得分:4)

正确的语法是......

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%'