首页 > 解决方案 > 如何将多个结果连接到oracle中的一列?

问题描述

我有以下疑问我有以下问题,下面我显示我的表格

              customers

 id name     client_type  date
 5  Fernando   5          27/04/2020
 6  paco       6          27/04/2020
 7  jose       5          27/04/2020
 8  angel      6          27/04/2020
 9  maria      6          27/04/2020

我有以下查询

select client_type from customers where date = sysdate group by client_type;

返回以下结果

type_clients
 5
 6

我需要的是返回以下结果

type_clients
5,6

我试过以下

select listgg (client_type, ',') within group (order by client_type)
  from CUSTOMERS
 where date = sysdate

但我返回了更多结果

type_clients
5,5,6,6,6

他们会帮助我解决我遇到的问题,非常感谢

标签: oracle

解决方案


如果您使用的是 Oracle 12C 或更高版本,您可以直接在 LISTAGG 中使用 distinct 子句 -

select listgg (distinct client_type, ',') within group (order by client_type)
  from CUSTOMERS
 where date = sysdate

但是,如果您使用低于 12C,则必须使用以下代码 -

select listgg (client_type, ',') within group (order by client_type)
  from (select distinct client_type
          from CUSTOMERS
         where date = sysdate)

推荐阅读