我试图重新配置下面的sql,以仅在Max(Field)!= 3时提取记录,但在下面不断出现错误(详细信息)。
这是添加Where Max(field)!= 3之前的代码
SELECT P.Code,
MAX(PW.v1) AS V1
FROM SW
INNER JOIN S ON SW.S_Id = S.Id
INNER JOIN PW ON SW.PW_Id = PW.Id
INNER JOIN PON S.P_Id = P.id
WHERE S.P_Id = P.id
GROUP BY P.Code
我的尝试
SELECT P.Code,
MAX(PW.v1) AS V1
FROM SW
INNER JOIN S ON SW.S_Id = S.Id
INNER JOIN PW ON SW.PW_Id = PW.Id
INNER JOIN PON S.P_Id = P.id
WHERE S.P_Id = P.id
AND (SELECT MAX(PW.v1)
FROM SW AS SW2
WHERE SW.PWId = SW2.PW_Id) != 3
GROUP BY P.Code
这是我得到的错误,不确定该怎么做: 除非聚集在HAVING子句或选择列表中包含的子查询中,并且聚集的列是外部引用,否则聚集可能不会出现在WHERE子句中。
答案 0 :(得分:1)
使用HAVING子句可以实现对聚合结果进行过滤的传统方法。我还删除了不必要的WHERE子句,因为您已经加入了该列上的那两个表。这是查询:
SELECT P.Code
,MAX(PW.v1) AS V1
FROM SW
INNER JOIN S
ON SW.S_Id = S.Id
INNER JOIN PW
ON SW.PW_Id = PW.Id
INNER JOIN P
ON S.P_Id = P.id
GROUP BY P.Code
HAVING MAX(PW.v1)!=3;