除非在子查询中,否则聚合可能不会出现在WHERE子句中

时间:2011-05-13 12:34:54

标签: c# sql

我正在尝试使用以下代码:

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

但我最终收到以下错误:

  

聚合可能不会出现在   WHERE子句,除非它在一个   HAVING子句中包含的子查询   或选择列表,列为   聚合是外部参考,   SELECT dbo。[PatRoster]。* FROM   dbo。[PatRoster]在哪里PatID =   @PatIDParam AND   EffectiveEnrollmentDate IN(选择   MAX(EffectiveEnrollmentDate))

5 个答案:

答案 0 :(得分:2)

您没有指定要从此处查询的表源:

(Select MAX(EffectiveEnrollmentDate))

将其更改为:

(Select MAX(EffectiveEnrollmentDate) FROM PatRoster)

答案 1 :(得分:2)

您的查询无效 - Select MAX(EffectiveEnrollmentDate)未完成;它必须从该子查询中的某个地方选择EffectiveEnrollmentDate

此外,MAX()只返回一个值,因此不需要IN - 您可以直接进行比较运算符=

答案 2 :(得分:0)

正如错误消息所示,正确的方法是使用子查询:

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

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

子查询中的聚合不能超过外部查询的值:

AND EffectiveEnrollmentDate IN (Select MAX(EffectiveEnrollmentDate))

你想要做的是:

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