sql >> Database teknologi >  >> RDS >> Oracle

Sådan fjerner jeg dubletter fra listagg

Vælg først DISTINCT værdier, du har brug for, og anvend derefter LISTAGG på dem. Her er et eksempel baseret på Scotts skema.

SQL> -- Duplicate jobs within the department
SQL> select deptno, listagg(job, ', ') within group (order by job) jobs
  2  from emp
  3  group by deptno;

    DEPTNO JOBS
---------- ------------------------------------------------------------
        10 CLERK, MANAGER, PRESIDENT
        20 ANALYST, ANALYST, CLERK, CLERK, MANAGER
        30 CLERK, MANAGER, SALESMAN, SALESMAN, SALESMAN, SALESMAN

SQL>
SQL> -- This won't work - DISTINCT can't be used in LISTAGG
SQL> select deptno, listagg(distinct job, ', ') within group (order by job) jobs
  2  from emp
  3  group by deptno;
select deptno, listagg(distinct job, ', ') within group (order by job) jobs
               *
ERROR at line 1:
ORA-30482: DISTINCT option not allowed for this function


SQL>
SQL> -- So - select distinct jobs first, then apply LISTAGG to it
SQL> select x.deptno, listagg(x.job, ', ') within group (order by x.job) jobs
  2  from (select distinct deptno, job
  3        from emp) x
  4  group by x.deptno;

    DEPTNO JOBS
---------- ------------------------------------------------------------
        10 CLERK, MANAGER, PRESIDENT
        20 ANALYST, CLERK, MANAGER
        30 CLERK, MANAGER, SALESMAN

SQL>


  1. ON DELETE CASCADE-indstillingen er ikke genereret, når du bruger ddl-skemagenerering på Mysql

  2. Brug streng [][] med ngpsql

  3. SQL server lagret procedure returnerer en tabel

  4. Søgning efter databaseobjekter og tabeldata i SQL Server