开发者

An aggregate may not appear in the WHERE clause unless it is in a subquery

I'm trying to use the following code:

m_Set.ClearQueryInfo();
m_Set.SetParameterWhere("PatID = @PatIDParam 开发者_Go百科AND EffectiveEnrollmentDate IN (Select MAX(EffectiveEnrollmentDate))");
m_Set.SetWhere("PatID = ? AND EffectiveEnrollmentDate IN (Select MAX(EffectiveEnrollmentDate))");
m_Set.SetNumParams(1);
m_Set.SetParam("@PatIDParam", 1, PatIDParam.ToString());

but I end up receiving the following 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, SELECT dbo.[PatRoster].* FROM dbo.[PatRoster] WHERE PatID = @PatIDParam AND EffectiveEnrollmentDate IN (Select MAX(EffectiveEnrollmentDate))


Your query is not valid - Select MAX(EffectiveEnrollmentDate) is not complete; it has to select EffectiveEnrollmentDate from somewhere in that subquery.

Also, MAX() only ever returns a single value, so there is no need for IN - you can just do straight comparison operator =.


You're not specifying the table source to query from here:

(Select MAX(EffectiveEnrollmentDate))

Change it to:

(Select MAX(EffectiveEnrollmentDate) FROM PatRoster)


As the error message suggests, the correct way to do this is with a subquery:

select bar.foo
from bar
where bar.foo = (select max(subbar.foo) from bar as subbar); -- subquery


The subquery: (Select MAX(EffectiveEnrollmentDate)) lacks a source, it cannot refer to the outer query

SELECT dbo.[PatRoster].* 
FROM dbo.[PatRoster] 
WHERE PatID = @PatIDParam AND EffectiveEnrollmentDate = (Select MAX(EffectiveEnrollmentDate) FROM dbo.[PatRoster])


You can't have an agregate in a sub query over the values of outer query:

AND EffectiveEnrollmentDate IN (Select MAX(EffectiveEnrollmentDate))

What you want to do is this:

SELECT dbo.[PatRoster].*
  FROM dbo.[PatRoster]
 WHERE PatID = @PatIDParam
   AND EffectiveEnrollmentDate = (Select MAX(EffectiveEnrollmentDate)
                                    FROM dbo.[PatRoster]
                                   WHERE PatID = @PatIDParam)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜