mysql group by summa列

时间:2013-05-07 22:25:07

标签: mysql group-by

我已经解决了这个问题:

SELECT round(avg(total_kpi),2) as avg_kpi, 
case when avg(total_kpi) < 3 then 'NEG' 
     when avg(total_kpi)>3 then 'POS' end  as kpi, 
count(gender) as gender,  
gender,  
round(avg(locacion),2) as avg_locacion, 
round(avg(tiempo),2) as avg_tiempo, 
round(avg(servicio),2) as avg_servicio, 
round(avg(calidad),2) as avg_calidad 
FROM datellig_ift.a02_view_kpi_2 
WHERE id_man_medicion=4 
group by 
case when avg(total_kpi) < 3 then 'NEG' 
     when avg(total_kpi) > 3 then 'POS' end

我需要按第2列对数据进行分组。分组时,mysql拒绝。
对不起,我一直在寻找一些帖子,但不明白为什么不工作。 感谢。

错误讯息:

  

#1111 - 无效使用群组功能

2 个答案:

答案 0 :(得分:1)

AVG()不能出现在GROUP BY子句中,因为它是“分组依据”或“聚合”功能。

有关所有聚合函数的详细信息,请参阅http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

根据您的跟进,我猜这个查询适合您:

SELECT
    IF(total_kpi < 3, 'NEG', 'POS') AS type,
    gender,  
    count(*) AS members,  
    round(avg(total_kpi),2) as avg_kpi, 
    round(avg(locacion),2) as avg_locacion, 
    round(avg(tiempo),2) as avg_tiempo, 
    round(avg(servicio),2) as avg_servicio, 
    round(avg(calidad),2) as avg_calidad 
FROM
    datellig_ift.a02_view_kpi_2 
WHERE
   id_man_medicion = 4 
GROUP BY
    total_kpi < 3, 
    gender

答案 1 :(得分:0)

昨晚我终于找到了解决方案。由于我的评价很低,不允许回答我的问题。然而罗斯史密斯二世帮助我,并检查他提出的解决方案我发现它也工作正常。这是我做的:

SELECT count(total_kpi) as q_kpi, 
case when total_kpi < 3 then  'NEG'  when total_kpi>3 then  'POS'  end  as kpi, 
count(gender) as gender, 
gender, 
round(avg(locacion),2) as avg_locacion, 
round(avg(tiempo),2) as avg_tiempo, 
round(avg(servicio),2) as avg_servicio,
round(avg(calidad),2) as avg_calidad 
FROM datellig_ift.a02_view_kpi_2  where id_man_medicion=4 GROUP BY 2, 4

感谢罗斯史密斯,你的意见导致找到答案。