如何消除Oracle中多个LISTAGG编辑列的重复项

时间:2014-05-07 21:14:20

标签: sql oracle11g oracle-sqldeveloper

我在以下脚本中从listagg函数中消除重复值时缺少什么逻辑。?

以下sys.privs表:

SQL> desc sys.privs
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 GRANTEE                                            VARCHAR2(30 CHAR)
 GRANTED_ROLE                              NOT NULL VARCHAR2(30)
 PRIVILEGE                                 NOT NULL VARCHAR2(40)
 OWNER                                     NOT NULL VARCHAR2(30)
 TABLE_NAME                                NOT NULL VARCHAR2(30)

以下是脚本

SELECT grantee,
     LISTAGG(granted_role, '-') WITHIN GROUP (ORDER BY granted_role) AS granted_role,
     LISTAGG(privilege, '-') WITHIN GROUP (ORDER BY privilege) AS privs,
     owner,
     table_name
FROM (
     SELECT UNIQUE
            grantee,
            granted_role,
            privilege,
            owner,
            table_name
       FROM sys.privs
     )
GROUP BY grantee, owner, table_name;

1 个答案:

答案 0 :(得分:1)

您可以利用listagg()忽略NULL值的事实来实现此目的。因此,使用row_number()枚举重复项,然后只需输入第一个值:

SELECT grantee,
       LISTAGG(CASE WHEN seqnum_granted_role = 1 THEN granted_role END, '-')
           WITHIN GROUP (ORDER BY granted_role) AS granted_role,
       LISTAGG(CASE WHEN seqnum_privilege = 1 THEN privilege END, '-')
           WITHIN GROUP (ORDER BY privilege) AS privs,
       owner,
       table_name
FROM (SELECT grantee, granted_role, privilege,
             owner, table_name,
             ROW_NUMBER() OVER (PARTITION BY grantee, owner, table_name, granted_role
                                ORDER BY grantee
                               ) as seqnum_granted_role,
             ROW_NUMBER() OVER (PARTITION BY grantee, owner, table_name, privilege
                                ORDER BY grantee
                               ) as seqnum_privilege
       FROM sys.privs
     ) p
GROUP BY grantee, owner, table_name;