select device_id,university, count(question_id) as question_cnt, sum(if(result='right',1,0)) as right_question_cnt FROM (select a.device_id,university,question_id,result,date from user_profile a left ...