where子句中的GROUP BY + SUM

时间:2014-04-23 14:14:28

标签: 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 
   sup=0 
GROUP BY grupo 
ORDER BY fecha_aprobacion ASC

MySQL返回:

 #1054 - Unknown column 'ap' in 'where clause'

因为" ap"来自sum,它不是行列。

是否有针对此的SQL解决方法?

2 个答案:

答案 0 :(得分:6)

您不能在WHERE子句中引用别名,因为查询的select部分是最后执行的,并且尚未创建别名。您也无法在WHERE中使用汇总函数,而应使用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 
   aprobado=0 
GROUP BY grupo,solicitante,fecha
HAVING  sum(aprobado)=0 AND sum(goe)= count(*) AND sum(goe)=1
ORDER BY fecha_aprobacion ASC

答案 1 :(得分:0)

你必须在你的条款

中引用它
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