业务场景
Mysql 查询数据后,同时需要根据其中某一个字段值进行排名处理,简单 sql 如图
SELECT id,user_id,sales_performance,(@i:=@i+1) rank from crm_account_user_performance_data,(SELECT @i:=0) t WHERE dept_id=307 ORDER BY sales_performance DESC;
复制代码
查询结果如图
其中: (@i:=@i+1)代表定义一个变量,每次增加 1,整体业务就是查询表数据同时根据 sales_performance 倒序后赋予排名。
Java 业务代码
先根据整表查询去重的 dept_id,再在各 dept_id 下查询数据的 sales_performance 倒序获得排名信息,后批量更新到数据库 rank 排名字段保存数据
List<Long> deptlist = accountUserPerformanceDataMapper.selectDeptIdsByAccountTime(date);if (CollectionUtils.isNotEmpty(deptlist)) { //遍历为每个部门下人员进行业绩排序 for (Long deptId : deptlist) { List<AccountUserPerformanceData> list = accountUserPerformanceDataMapper.selectRankByDeptId(deptId); //批量更新本部门排序 accountUserPerformanceDataMapper.updateRankBatch(list); }}
复制代码
xml 代码,获取 dept_id 集合
<select id="selectDeptIdsByAccountTime" parameterType="Date" resultType="java.lang.Long"> SELECT DISTINCT dept_id FROM crm_account_user_performance_data WHERE account_time = #{accountTime}</select>
复制代码
获取各 dept_id 内部根据 sales_performance 倒序排列的序号值
<select id="selectRankByDeptId" parameterType="Long" resultMap="AccountUserPerformanceDataResult"> SELECT id,user_id,(@i:=@i+1) rank from crm_account_user_performance_data,(SELECT @i:=0) t WHERE dept_id=#{deptId} ORDER BY sales_performance DESC</select>
复制代码
批量更新到数据表中
<update id="updateRankBatch" parameterType="List"> update crm_account_user_performance_data set rank = case id <foreach collection="list" item="account" separator=" "> when #{account.id} then #{account.rank} </foreach> end where id in <foreach collection="list" item="account" open="(" separator="," close=")"> #{account.id} </foreach></update>
复制代码
注:本文设计 Mysql 获取数据排序序号及批量更新数据库相关操作,日常工作记录,需要的博友自行参考哈。
评论