查询中的平均值 - mysql

时间:2011-07-03 18:08:58

标签: mysql sql aggregate-functions

我有这个查询

  SELECT salary
    FROM worker W
    JOIN single_user U ON u.users_id_user = W.single_user_users_id_user
    JOIN university_has_single_user US ON US.single_user_users_id_user = U.users_id_user
    JOIN course C ON C.id_course = US.course_id_course
    JOIN formation_area FA ON FA.id_formation_area = C.formation_area_id_formation_area
   WHERE FA.area = "Multimédia"
GROUP BY users_id_user

......给出了这个输出:

salary
--------
1400.00
800.00

如何计算此输出的平均值?如果我添加:

SELECT round(avg (salary), 0) 

...输出再次是1400.00和800.00,而不是平均值(因为分组依据)。

1 个答案:

答案 0 :(得分:1)

使用:

 SELECT AVG(DISTINCT salary)
   FROM worker W
   JOIN single_user U ON u.users_id_user = W.single_user_users_id_user
   JOIN university_has_single_user US ON US.single_user_users_id_user = U.users_id_user
   JOIN course C ON C.id_course = US.course_id_course
   JOIN formation_area FA ON FA.id_formation_area = C.formation_area_id_formation_area
  WHERE FA.area = "Multimédia"

由于salary列未包含在聚合中,per the documentation, the values you see are arbitrary (can't be guaranteed 100% of the time)

通常,您需要一个派生表来获取不同值的平均值,但MySQL's AVG supports using DISTINCT within it