在 Oracle 11g 中,您需要执行几个步骤:
SQL> select * From v$version where rownum = 1;
BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
SQL> select * From test;
ID CO CO CO
---------- -- -- --
1 P1 d1 V1
2 P1 d2 V1
3 P3 d1 V1
4 P3 d2 V1
5 P4 d1 V1
6 P4 d2 V1
6 rows selected.
SQL>
SQL> with
2 c1 as (select distinct col1 from test),
3 c2 as (select distinct col2 from test),
4 c3 as (select distinct col3 from test),
5 --
6 c1l as (select listagg(col1, ';') within group (order by col1) cl1 from c1),
7 c2l as (select listagg(col2, ';') within group (order by col2) cl2 from c2),
8 c3l as (select listagg(col3, ';') within group (order by col3) cl3 from c3)
9 --
10 select cl1 ||';'|| cl2 ||';'|| cl3 as result
11 from c1l cross join c2l cross join c3l;
RESULT
--------------------------------------------------------------------------------
P1;P3;P4;d1;d2;V1
SQL>
在更高版本中 - 支持
distinct
内的 listagg
- 事情变得更简单:
SQL> select banner from v$version;
BANNER
--------------------------------------------------------------------------------
Oracle Database 21c Express Edition Release 21.0.0.0.0 - Production
SQL> select
2 listagg(distinct col1, ';') within group (order by col1) ||';'||
3 listagg(distinct col2, ';') within group (order by col2) ||';'||
4 listagg(distinct col3, ';') within group (order by col3) result
5 from test;
RESULT
--------------------------------------------------------------------------------
P1;P3;P4;d1;d2;V1
甚至
SQL> select
2 listagg(distinct col1, ';') ||';'||
3 listagg(distinct col2, ';') ||';'||
4 listagg(distinct col3, ';') result
5 from test;
RESULT
--------------------------------------------------------------------------------
P1;P3;P4;d1;d2;V1
SQL>