###################################################################
业务需求:根据评价类别(evaluate_type)计算技能评分(score_grade)平均分
#######################普通sql##############################################
SELECT AVG(t.score_grade) as A FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=1 ;
SELECT AVG(t.score_grade) as B FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=2 ;
SELECT AVG(t.score_grade) as C FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=3 ;
SELECT AVG(t.score_grade) as D FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=4 ;
######################使用union ALL####################
SELECT AVG(t.score_grade) as A FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=1
UNION ALL
SELECT AVG(t.score_grade) as B FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=2
UNION ALL
SELECT AVG(t.score_grade) as C FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=3
UNION ALL
SELECT AVG(t.score_grade) as D FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=4
#####################使用子查询######################
SELECT DISTINCT
(SELECT AVG(t.score_grade) FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=1 )as a,
(SELECT AVG(t.score_grade) FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=2) as b,
(SELECT AVG(t.score_grade) FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=3 ) as c,
(SELECT AVG(t.score_grade) FROM `t_user_evaluate` t where t.matron_id=11 AND t.evaluate_type=4 ) as d
FROM `t_user_evaluate`
##################使用CASE WHEN 条件 THEN 值 END ########################
SELECT AVG(CASE WHEN t.evaluate_type=1 THEN t.score_grade end) as a,
AVG(CASE WHEN t.evaluate_type=2 THEN t.score_grade end) as b,
AVG(CASE WHEN t.evaluate_type=3 THEN t.score_grade end) as c,
AVG(CASE WHEN t.evaluate_type=4 THEN t.score_grade end) as d
FROM `t_user_evaluate` t where t.matron_id=11 ;
原文地址:http://blog.51cto.com/1929297/2110613