2011-07-03 91 views
0

我有這個疑問平均查詢 - mysql的

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,而不是avg(因爲group by)。

回答

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

+0

很好,謝謝 – anvd

+0

我有的問題就是比如有兩個人的課有兩次重複的工資。現在罰款 – anvd

+0

但對於不同的人也可以是相同的工資.. 我的問題是 - 是否需要把明顯的那裏? –