select qd.difficult_level, ROUND(COUNT(if (qpd.result = 'right',1,NULL))/COUNT(qpd.result),4) #对的行数 / 总行数 AS correct_rate FROM user_profile AS up JOIN question_practice_detail AS qpd ON up.device_id = qpd.device_id JOIN question_detail AS qd ON qpd.question_id = qd.question_id WHERE up.university = '浙江大学' GROUP BY qd.difficult_level ORDER BY correct_rate
- : 这种写法在IF条件为true时返回1,为false时返回NULL。COUNT函数会忽略NULL值,因此只会统计条件为true的行数。
- COUNT(IF(qpd.result = 'right', 1, 0)): 这种写法在IF条件为true时返回1,为false时返回0。COUNT函数会统计所有非NULL的值,包括0,因此会统计条件为true和条件为false的行数。
总的来说,两者的区别在于对于条件为false
时的值的处理。如果你想统计所有满足条件的行数,包括条件为false
的行,那么使用COUNT(IF(qpd.result = 'right', 1, 0))
更合适。如果你只关心条件为true
的行数,那么使用COUNT(IF(qpd.result = 'right', 1, NULL))
可能更清晰。