按相关问题分组。如何从未按列分组的列中获取 unique/distinct 值?

Group by related question. How to get the unique/distinct values, from a column that is not the grouped by column?

这是简化的查询:

select column1, count(*), emails
from table1 group by column1;

但是,“电子邮件”部分会引发错误,因为分组依据是针对第 1 列,而不是针对电子邮件列。我想要的是获取所有 UNIQUE/DISTINCT 电子邮件,因此查询结果将如下所示:

col1 计数 电子邮件
val1 4 电子邮件 1 电子邮件 2 电子邮件 3
val2 10 email4 email5 email6 email7
val3 2 电子邮件 8 电子邮件 9

你要的是listagg(distinct):

select column1, count(*),
       listagg(distinct email, ',') within group (order by email)
from table1
group by column1;

但是,Oracle 不支持 distinctlistagg()。一种解决方法是:

select column1, count(*),
       listagg(case when seqnum = 1 then email end, ',') within group (order by email) as emails
from (select t1.*,
             row_number() over (partition by column1, email order by email) as seqnum
      from table1 t1
     ) t1
group by column1;