当前位置:网站首页>Mysql 生成排序序号
Mysql 生成排序序号
2022-08-03 14:07:00 【InfoQ】
业务场景
Mysql查询数据后,同时需要根据其中某一个字段值进行排名处理,简单sql如图
SELECT id,user_id,sales_performance,(@i:[email protected]+1) rank from crm_account_user_performance_data,(SELECT @i:=0) t WHERE dept_id=307 ORDER BY sales_performance DESC;查询结果如图

其中: (@i:[email protected]+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:[email protected]+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获取数据排序序号及批量更新数据库相关操作,日常工作记录,需要的博友自行参考哈。
边栏推荐
- 【框架】idea找不到xxx依赖项怎么办
- Day2:面试必考题目
- 哥斯拉加密WebShell过杀软
- APT组织最喜欢的工具 Cobalt Strike (CS) 实战
- Chrome browser corresponding driver_chrome mobile browser
- STL简介
- PostgreSQL 每周新闻 2022-7-27
- LARS (Least Angle Regression)
- MySQL知识总结 (十二) 数据库相关概念
- 为什么手动启动GBase 8c数据库中GTM节点,起不来。显示“Run cmd failed:scp: /tmp/gtm_gtm1.server: Permission denied”
猜你喜欢
随机推荐
W11的右键如何改成和W10一样?(一行命令即可解决!)
Huffman tree
位级运算之计算整数位级表示奇偶性
你把 vite打包 玩明白
如何把MapGIS的区文件转为ArcGIS的SHAPE面文件
工作流自动化,低代码是解决关键
如何在 UE4 中制作一扇自动开启的大门
进程通信的方式
Nanoprobes 金纳米颗粒标记试剂丨1.4 nm Nanogold 标记试剂
鸿湖万联扬帆富设备开发板正式合入OpenHarmony主干
投资75亿卢比!印度宣布建首座存储芯片组装和封测工厂,将于12月量产
MySQL【视图】
将移位距离和假设外推到非二值化问题
连亏四个月,赚不回电费,预制菜经销商恐成“韭菜”?
中国菜刀原理与实践
Zhang Le: The Golden Triangle of R&D Efficiency and Practice in the Field of Demand and Agile Collaboration|Live Review
网络通信的过程
冰蝎加密 WebShell 过杀软
数字孪生的4个最佳实践
English语法_介词 - 概述









