聚合不能出现在 WHERE 子句中,除非它位于子查询中

本文关键字:查询 不能 子句 WHERE | 更新日期: 2023-09-27 17:56:26

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

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 子句中包含的子查询 或选择列表,并且列 聚合是外部引用, 选择"dbo"。[Pat名册].* 来自 德博。[花名册] 其中 PatID = @PatIDParam和 生效注册日期 IN (选择 最大(有效注册日期))

聚合不能出现在 WHERE 子句中,除非它位于子查询中

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

此外,MAX()只返回单个值,因此无需IN - 您可以直接比较运算符=

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

(Select MAX(EffectiveEnrollmentDate))

将其更改为:

(Select MAX(EffectiveEnrollmentDate) FROM PatRoster)

正如错误消息所暗示的那样,执行此操作的正确方法是使用子查询:

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

子查询:(Select MAX(EffectiveEnrollmentDate))缺少源,则无法引用外部查询

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

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

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)