从表中的多列中选择不同的值并在一列中返回结果

问题描述 投票:0回答:1

我的数据库中有一个包含多个列的表,我想从这些列中选择不同的值并将结果连接到一个字符串中。如何在单个 SQL 查询中实现此目的? @数据库甲骨文: plsql

sql oracle plsql oracle11g
1个回答
0
投票

在 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>
© www.soinside.com 2019 - 2024. All rights reserved.