需要使用SQL将多行连接成单个单元格吗?

时间:2011-11-04 16:08:51

标签: sql database oracle oracle11g

目前我写道:

SELECT IT_ID, SUBSTR (SYS_CONNECT_BY_PATH (grp , ','), 2) GROUPS
FROM (SELECT U.IT_ID, LAST_NAME, FIRST_NAME, GRP, ROW_NUMBER() OVER (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

返回:

IT_ID   GROUPS

afz23   ADMIN
afz23   ADMIN,QA
alv77   ADMIN,QA,USER
jaj23   ADMIN,QA,USER,USER
klo26   ADMIN,QA,USER,USER,PROD
klo26   ADMIN,QA,USER,USER,PROD,ADMIN
klo26   ADMIN,QA,USER,USER,PROD,ADMIN,QA
mav45   ADMIN,QA,USER,USER,PROD,ADMIN,QA,ADMIN

我无法弄清楚如何在遇到新用户后重置它?即使用户不属于他们,它似乎也在继承以前的群组。

我需要看看:

IT_ID   GROUPS

afz23   ADMIN,QA
alv77   USER
jaj23   USER
klo26   PROD,ADMIN,QA
mav45   ADMIN

1 个答案:

答案 0 :(得分:0)

这里有三件事你需要做。

首先,您需要在row_number函数中添加一个分区,以便从每个IT_ID的1开始编号。您还需要将IT_ID列添加到connect by,以便它只使用具有相同IT_ID值的行。最后,您需要按it_id列进行分组以删除重复的行。

最终查询将是

with ECG_IT_USERS as (
  select 'afz23' as it_id from dual union all
  select 'alv77' as it_id from dual union all
  select 'jaj23' as it_id from dual union all
  select 'klo26' as it_id from dual union all
  select 'mav45' as it_id from dual
),
securegroups as (
  select 'afz23' as it_id, 'ADMIN' as grp from dual union all
  select 'afz23' as it_id, 'QA' as grp from dual union all
  select 'alv77' as it_id, 'USER' as grp from dual union all
  select 'jaj23' as it_id, 'USER' as grp from dual union all
  select 'klo26' as it_id, 'PROD' as grp from dual union all
  select 'klo26' as it_id, 'ADMIN' as grp from dual union all
  select 'klo26' as it_id, 'QA' as grp from dual union all
  select 'mav45' as it_id, 'ADMIN' as grp from dual
)
SELECT 
  IT_ID, 
  Max(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
----- --------------------
alv77 USER
afz23 ADMIN,QA
jaj23 USER
mav45 ADMIN
klo26 PROD,ADMIN,QA

编辑:我添加了带有一些示例数据的with子句,这对我运行没有任何问题,尽管我注释掉了last_name和first_name列,因为它们没有对最终查询,我在连接条件周围添加了一些括号。

也许从上面的查询开始就付出代价,检查它最初是否适用于您并在适当时进行修改。