需求:根据科室分组,找出该科室下每个项目中使用最多的前3名

SELECT
 execute_dept_id,counts,
 item_id ,
 if(@type = execute_dept_id,@rank := @rank + 1,@rank := 1 ) AS rank_no,
 @type := execute_dept_id as dummy  
FROM
 ( SELECT count( item_id ) AS counts, ifnull(execute_dept_id,0) as execute_dept_id, item_id FROM outpat_application_form    GROUP BY execute_dept_id, item_id ORDER BY counts DESC ) a
 ,(select @rank := 0,@type := 0) b
GROUP BY
 execute_dept_id,
 item_id
HAVING
 rank_no <= 3;