An aggregate may not appear in the WHERE clause unless it is in a subquery
我正在尝试使用以下代码:
1 2 3 4 5 | m_Set.ClearQueryInfo(); m_Set.SetParameterWhere("PatID = @PatIDParam 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()); |
但我最终收到以下错误:
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))
您的查询无效 -
另外,
您没有指定要从这里查询的表源:
1 | (Select MAX(EffectiveEnrollmentDate)) |
改成:
1 | (Select MAX(EffectiveEnrollmentDate) FROM PatRoster) |
您不能在子查询中对外部查询的值进行聚合:
你想做的是:
1 2 3 4 5 6 | SELECT dbo.[PatRoster].* FROM dbo.[PatRoster] WHERE PatID = @PatIDParam AND EffectiveEnrollmentDate = (Select MAX(EffectiveEnrollmentDate) FROM dbo.[PatRoster] WHERE PatID = @PatIDParam) |
子查询:
1 2 3 | SELECT dbo.[PatRoster].* FROM dbo.[PatRoster] WHERE PatID = @PatIDParam AND EffectiveEnrollmentDate = (Select MAX(EffectiveEnrollmentDate) FROM dbo.[PatRoster]) |
正如错误消息所暗示的,正确的方法是使用子查询:
1 2 3 | select bar.foo from bar where bar.foo = (select max(subbar.foo) from bar as subbar); -- subquery |