mysql 使用group by統計數據排序並輸出序號

以下演示查詢用戶回答數量從高到低降序查詢,並且輸出當前用戶回答排名序號:
關鍵查詢ROUND(@rownum := @rownum + 1) rownum ,(SELECT @rownum := 0) r

select t.rownum rownum,t.count count from (
	select a.user_id,a.count,ROUND(@rownum := @rownum + 1) rownum from (
		select user_id,count(1) count from ask_answers
		where opt_type =1
		<if test="null!=startTime and ''!=startTime">
		<![CDATA[ and created_at >= #{startTime,jdbcType=VARCHAR} ]]>
		</if>
		<if test="null!=endTime and ''!=endTime">
		<![CDATA[ and created_at <= #{endTime,jdbcType=VARCHAR} ]]>
		</if>
		GROUP by user_id
		order by count(1) DESC,user_id asc
	) a,(SELECT @rownum := 0) r
) t where t.user_id = #{userId,jdbcType=INTEGER}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章