listagg 数据到可用格式?

listagg data to useable format?

这是我第一次使用 LISTAGG 函数,我很困惑。我可以很容易地 select 数据,但是 USERS 列的字符之间都有空格,并且在尝试复制粘贴时,没有复制该列的数据。我试过两种不同的 IDE。我做错了什么吗?

示例:

select course_id, listagg(firstname, ', ') within group (order by course_id) as users
    from (
      select distinct u.firstname, u.lastname, u.student_id, cm.course_id
      from course_users cu
      join users u on u.pk1 = cu.users_pk1
      join course_main cm on cm.pk1 = cu.crsmain_pk1
      and cm.course_id like '2015SP%'
      )
group by course_id;

产量:

我也有类似的问题,原来是编码的问题。我这样解决了这个问题(如果需要,更改为另一种编码):

...listagg(convert(firstname, 'UTF8', 'AL16UTF16'), ', ')...

您的 firstname 列似乎定义为 nvarchar2:

with t as (
  select '2015SP.BOS.PPB.556.A'as course_id,
    cast('Alissa' as nvarchar2(10)) as firstname
  from dual
  union all select '2015SP.BOS.PPB.556.A'as course_id,
    cast('Dorothea' as nvarchar2(10)) as firstname
  from dual
)
select course_id, listagg(firstname, ', ')
  within group (order by course_id) as users
from t
group by course_id;

COURSE_ID            USERS                         
-------------------- ------------------------------
2015SP.BOS.PPB.556.A 

... 而且我也无法 copy/paste 来自 SQL Developer 的用户值,但它显示有空格,正如您从 SQL*Plus 中看到的那样:

COURSE_ID            USERS
-------------------- ------------------------------
2015SP.BOS.PPB.556.A  A l i s s a,  D o r o t h e a

如文档所述,listagg() 函数总是 returns varchar2(或 raw),因此传入 nvarchar2 值会导致隐式转换会丢弃您的结果。

如果您坚持使用该数据类型的列,您可以在 listagg 调用中将其转换为 varchar2

column users format a30
with t as (
  select '2015SP.BOS.PPB.556.A'as course_id,
    cast('Alissa' as nvarchar2(10)) as firstname
  from dual
  union all select '2015SP.BOS.PPB.556.A'as course_id,
    cast('Dorothea' as nvarchar2(10)) as firstname
  from dual
)
select course_id, listagg(cast(firstname as varchar2(10)), ', ')
  within group (order by course_id) as users
from t
group by course_id;

COURSE_ID            USERS                         
-------------------- ------------------------------
2015SP.BOS.PPB.556.A Alissa, Dorothea               

但您可能根本不希望它成为 nvarchar2

显然这是 11 中的一个已知(未解决?)错误。TO_CHAR() 对我有用...

SELECT wiporderno, LISTAGG(TO_CHAR(medium), ',') WITHIN GROUP(ORDER BY wiporderno) AS jobclassification 

...介质是有问题的 column/data 类型。