0

我的SQL返回用戶標識與他們的角色列表,重點是將所有角色(組)連接成一行。目前,它返回所有內容,但我只需要爲每個用戶返回一個條目,基本上是每個用戶具有該用戶最大的rn(行號)的條目。如何返回行數最多的行?

SELECT 
    IT_ID, 
    SUBSTR (SYS_CONNECT_BY_PATH (grp , ','), 2) GROUPS 
FROM (
    SELECT 
    U.IT_ID, 
    LAST_NAME, 
    BFIRST_NAME, 
    GRP, 
    ROW_NUMBER() OVER (partition by u.it_id ORDER BY U.IT_ID) rn, 
    COUNT(*) OVER() cnt 
FROM ECG_IT_USERS U 
JOIN SECUREGROUPS G ON U.IT_ID = G.IT_ID) 
START WITH rn = 1 
CONNECT BY rn = PRIOR rn + 1 and it_id = prior it_id 
Group by it_id 

它返回:

IT_ID GROUPS 
afz23 ADMIN 
afz23 ADMIN, QA 
klf44 USER 
klf44 USER, BUSINESS 

我需要返回

IT_ID GROUPS 
afz23 ADMIN, QA 
klf44 USER, BUSINESS 

回答

0

添加計算最大在每個IT_ID分區的行號的另一解析函數。然後選擇其中rn = max_rn的行。

0
select it_id, groups 
from 
(
    select 
     it_id 
     , groups 
     , row_number() over (partition by id_id order by length(groups) desc) rn 
    from 
     (
      SELECT 
      IT_ID, 
      SUBSTR (SYS_CONNECT_BY_PATH (grp , ','), 2) GROUPS 
      FROM (
      SELECT 
       U.IT_ID, 
       LAST_NAME, 
       BFIRST_NAME, 
       GRP, 
       ROW_NUMBER() OVER (partition by u.it_id ORDER BY U.IT_ID) rn, 
       COUNT(*) OVER() cnt 
      FROM ECG_IT_USERS U 
      JOIN SECUREGROUPS G ON U.IT_ID = G.IT_ID) 
      START WITH rn = 1 
      CONNECT BY rn = PRIOR rn + 1 and it_id = prior it_id 
      Group by it_id 
    ) 
) 
where rn = 1 
;