0

My SQL returns a list of user ID's with their roles, the point is to concatenate all roles (groups) into one line. Currently, it returns everything, but I just need to return one entry per user, basically the entry per user with the largest rn (row number) for that user.

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 returns:

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

I need to return

IT_ID   GROUPS
afz23   ADMIN, QA
klf44   USER, BUSINESS
Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
antonpug
  • 13,724
  • 28
  • 88
  • 129

3 Answers3

0

Add another analytic function that calculates the maximum of the row number over each IT_ID partition. Then select the row where rn = max_rn.

tobiasbayer
  • 10,269
  • 4
  • 46
  • 64
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
;
schurik
  • 7,798
  • 2
  • 23
  • 29
0

This is a problem. There's a very comprehensive answer on the topic here: SQL Select only rows with Max Value on a Column

Since time is now limited, I cannot work on your query. Not giving you the fish, but teaching how to fish.

Community
  • 1
  • 1
Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123