关于c#:聚合可能不会出现在WHERE子句中,除非它在子查询中

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))


您的查询无效 - Select MAX(EffectiveEnrollmentDate) 不完整;它必须从该子查询中的某处选择 EffectiveEnrollmentDate

另外,MAX() 只返回一个值,所以不需要 IN - 你可以直接做比较运算符 =.


您没有指定要从这里查询的表源:

1
(Select MAX(EffectiveEnrollmentDate))

改成:

1
(Select MAX(EffectiveEnrollmentDate) FROM PatRoster)


您不能在子查询中对外部查询的值进行聚合:

AND EffectiveEnrollmentDate IN (<s>Select MAX(EffectiveEnrollmentDate)</s>)

你想做的是:

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)

子查询:(Select MAX(EffectiveEnrollmentDate)) 缺少源,它不能引用外部查询

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