我的SQL返回一个用户ID列表及其角色,重点是将所有角色(组)连接成一行。目前,它返回所有内容,但我只需要为每个用户返回一个条目,基本上是每个用户的条目,该用户具有最大的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 :(得分:0)
添加另一个分析函数,用于计算每个IT_ID
分区上行号的最大值。然后选择rn = max_rn的行。
答案 1 :(得分: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
;
答案 2 :(得分:0)
这是一个greatest-n-per-group问题。这里有关于这个主题的非常全面的答案:SQL Select only rows with Max Value on a Column
由于现在时间有限,我无法处理您的查询。不给你鱼,但教你如何捕鱼。