我有一个看起来像这样的表:
╔════════════╦═════════╦═══════════╗
║ Machine_ID ║ User_ ID ║ User_Role ║
╠════════════╬═════════╬═══════════╣
║ Mach_001 ║ N00001 ║ 3 ║
║ Mach_001 ║ N00001 ║ 4 ║
║ Mach_001 ║ N00002 ║ 3 ║
║ Mach_001 ║ N00002 ║ 2 ║
║ Mach_002 ║ N00001 ║ 3 ║
║ Mach_002 ║ N00002 ║ 3 ║
╚════════════╩═════════╩═══════════╝
我正在尝试为每个User_Role
- Machine_ID
获取最高User_ID
的行:
╔════════════╦═════════╦═══════════╗
║ Machine_ID ║ User_ID ║ User_Role ║
╠════════════╬═════════╬═══════════╣
║ Mach_001 ║ N00001 ║ 4 ║
║ Mach_001 ║ N00002 ║ 3 ║
║ Mach_002 ║ N00001 ║ 3 ║
║ Mach_002 ║ N00002 ║ 3 ║
╚════════════╩═════════╩═══════════╝
我该怎么做呢?根据我的数据,我可能会有许多Machine_ID
- User_ID
个重复项,其中Role
级别不同,但我只是喜欢最高级别的角色。
编辑:
根据Gordon Linoff的回答,我得到了我想要的东西:
SELECT Machine_ID, User_ID, User_Role
FROM (SELECT ex_rt.*,
row_number() OVER (PARTITION BY Machine_ID, User_ID, ORDER BY User_Role DESC) AS seqnum
FROM ex_rt
) sub
WHERE seqnum = 1;
答案 0 :(得分:1)
在大多数数据库中,您可以使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by machine_name, user_ID order by user_role desc) as seqnum
from t
) t
where seqnum = 1;