Mysql where子句中的GROUP BY+SUM

Mysql where子句中的GROUP BY+SUM,mysql,sql,Mysql,Sql,我运行了这个查询 SELECT grupo, solicitante, sum(valuacion) as valuacion, fecha, count(*) as cant, sum(aprobado) as ap, sum(goe) as goe FROM presupuestos WHERE ap=0 AND goe=cant AND grupo>0 AND elim=0 AND

我运行了这个查询

SELECT 
   grupo, 
   solicitante, 
   sum(valuacion) as valuacion, 
   fecha, 
   count(*) as cant, 
   sum(aprobado) as ap, 
   sum(goe) as goe 
FROM 
   presupuestos
WHERE 
   ap=0 AND 
   goe=cant AND 
   grupo>0 AND 
   elim=0 AND 
   sup=0 
GROUP BY grupo 
ORDER BY fecha_aprobacion ASC
MySQL返回:

 #1054 - Unknown column 'ap' in 'where clause'
因为ap来自sum,而不是行-列


有SQL解决方法吗?

您必须在having子句中引用它

SELECT 
   grupo, 
   solicitante, 
   sum(valuacion) as valuacion, 
   fecha, 
   count(*) as cant, 
   sum(aprobado) as ap, 
   sum(goe) as goe 
FROM 
   presupuestos
WHERE 
   grupo>0 AND 
   elim=0 AND 
   sup=0 AND 
   goe=1 AND 
   aprobado=0 
GROUP BY grupo 
HAVING
   sum(aprobado) = 0 and
   count(*) = sum(goe)
ORDER BY 
   fecha_aprobacion ASC

你必须在你的having条款中提到这一点

SELECT 
   grupo, 
   solicitante, 
   sum(valuacion) as valuacion, 
   fecha, 
   count(*) as cant, 
   sum(aprobado) as ap, 
   sum(goe) as goe 
FROM 
   presupuestos
WHERE 
   grupo>0 AND 
   elim=0 AND 
   sup=0 AND 
   goe=1 AND 
   aprobado=0 
GROUP BY grupo 
HAVING
   sum(aprobado) = 0 and
   count(*) = sum(goe)
ORDER BY 
   fecha_aprobacion ASC

您不能在WHERE子句中引用别名,因为查询的select部分是最后执行的,而别名尚未生成。您也不能在WHERE中使用聚合函数,应使用have:


您不能在WHERE子句中引用别名,因为查询的select部分是最后执行的,而别名尚未生成。您也不能在WHERE中使用聚合函数,应使用have:


这将不起作用-你的WHERE子句中仍然有goe和cant-它们也应该移到HAVING子句。我还要指出,在这种情况下,GROUP BY是不合逻辑的。聚合函数中不包含的任何列都应包含在GROUP BY中。我知道MySQL将允许您这样做,但这并不正确。您可能需要将goe=1从where子句中删除到having中,但由于您有一个名为goe的列可以工作。goe=1和&aprobado=0在where子句中是我的错,它们不应该存在。检查主帖子中的原始查询,我编辑了它。这个答案适合我的需要。这不起作用-你的WHERE子句中仍然有goe和cant-它们也应该移到HAVING子句。我还要指出,在这种情况下,GROUP BY是不合逻辑的。聚合函数中不包含的任何列都应包含在GROUP BY中。我知道MySQL将允许您这样做,但这并不正确。您可能需要将goe=1从where子句中删除到having中,但由于您有一个名为goe的列可以工作。goe=1和&aprobado=0在where子句中是我的错,它们不应该存在。检查主帖子中的原始查询,我编辑了它。这个答案很适合我的需要。