如何根据RolePriority获取用户的最高优先级角色及对应Code
解决用户多角色下取最高优先级角色的问题
看起来你需要从用户-角色映射数据中,筛选出每个用户最高优先级的角色记录对吧?我结合你的示例数据,给你几种不同技术栈的实现方案,都是日常开发里常用的~
首先先明确需求核心:
- 每个用户可能关联多个角色,每个角色有
RolePriority数值(数值越大优先级越高,从你的示例能看出来:Rehman的Def优先级3>2,所以选中Def;Neha只有Des优先级1,直接选中) - 最终要得到每个用户对应的最高优先级角色的
Code、角色名等信息
方案1:SQL实现(最常用的数据库查询场景)
如果你的数据存在数据库里,用窗口函数可以轻松解决:
SELECT Code, Name, Role, RolePriority FROM ( SELECT Code, Name, Role, RolePriority, -- 按用户分组,组内按优先级降序编号 ROW_NUMBER() OVER (PARTITION BY Name ORDER BY RolePriority DESC) AS row_rank FROM your_table_name -- 替换成你的表名 ) ranked_data WHERE row_rank = 1;
补充说明:
PARTITION BY Name:把数据按用户分组ORDER BY RolePriority DESC:每个组内让优先级高的记录排在前面- 如果遇到同一个用户有多个相同最高优先级的角色,
ROW_NUMBER()会随机保留一条;要是想保留所有同优先级的角色,把ROW_NUMBER()换成RANK()即可
方案2:Python Pandas实现(数据分析/脚本场景)
如果用Python处理数据,Pandas的分组排序功能很方便:
import pandas as pd # 示例数据(可以替换成你的数据源) data = { 'Code': [1, 2, 3], 'Name': ['Rehman', 'Rehman', 'Neha'], 'Role': ['Abc', 'Def', 'Des'], 'RolePriority': [2, 3, 1] } df = pd.DataFrame(data) # 先按用户+优先级降序排序,再分组取每组第一条 result_df = df.sort_values( by=['Name', 'RolePriority'], ascending=[True, False] ).groupby('Name').head(1) # 输出结果 print(result_df)
运行后会直接得到你想要的结果:Rehman对应Def,Neha对应Des。如果要保留同最高优先级的所有角色,去掉.head(1)即可。
方案3:Java Stream API实现(后端开发场景)
如果是Java后端处理这类数据,用Stream API可以简洁完成分组筛选:
import java.util.*; import java.util.stream.Collectors; // 定义用户角色实体类 class UserRole { private int code; private String name; private String role; private int rolePriority; public UserRole(int code, String name, String role, int rolePriority) { this.code = code; this.name = name; this.role = role; this.rolePriority = rolePriority; } // Getter方法 public String getName() { return name; } public int getRolePriority() { return rolePriority; } public String getRole() { return role; } public int getCode() { return code; } @Override public String toString() { return String.format("Code: %d, Name: %s, Role: %s, RolePriority: %d", code, name, role, rolePriority); } } public class Main { public static void main(String[] args) { List<UserRole> userRoleList = Arrays.asList( new UserRole(1, "Rehman", "Abc", 2), new UserRole(2, "Rehman", "Def", 3), new UserRole(3, "Neha", "Des", 1) ); // 按用户名分组,每组保留优先级最高的角色 Map<String, UserRole> highestPriorityRoles = userRoleList.stream() .collect(Collectors.toMap( UserRole::getName, role -> role, // 合并规则:如果同一个用户有多个角色,保留优先级高的那个 (existingRole, newRole) -> existingRole.getRolePriority() > newRole.getRolePriority() ? existingRole : newRole )); // 输出结果 highestPriorityRoles.values().forEach(System.out::println); } }
运行后会输出每个用户的最高优先级角色记录,逻辑和前面的方案一致。
内容的提问来源于stack exchange,提问作者Niteesh Kumar
相关产品推荐
相关产品推荐

