5

可能重复:
如何在 Oracle 中将多行组合成逗号分隔的列表?

有人可以告诉我如何实现以下目标吗?

桌子:

efforts_id        cycle_name      release_name 
123               quarter         march 
123               half            april 
123               full            april
124               quarter         may

我的预期输出:

efforts_id        cycle_name            release_name 
123               quarter,half,full     march,april
124               quarter               may

我是甲骨文的初学者,所以不知道该怎么做。任何帮助,将不胜感激。

谢谢

4

4 回答 4

7

您需要的是“字符串聚合”。Tim Hall 的优秀网站显示了您拥有的替代方案,具体取决于您拥有的 Oracle 的确切版本:http ://www.oracle-base.com/articles/misc/string-aggregation-techniques.php

在 11gR2(撰写本文时当前版本)中,您应该使用 listagg 函数:

select
  efforts_id,
  listagg(cycle_name, ',') within group (order by cycle_name) as cycle_name,
  listagg(release_name, ',') within group (order by release_name) as release_name
from my_table
group by efforts_id;

请注意,Oracle 不支持使用 wm_concat 函数...

于 2012-10-30T15:45:42.783 回答
6

您将要使用LISTAGG()来执行此任务。其他答案不会删除任何重复值,要删除重复项,您可以使用类似于以下的内容:

select c.efforts_id, 
  c.cycle_name,
  listagg(r.release_name, ', ') within group (order by c.efforts_id) as release_name
from
(
  select efforts_id,
    listagg(cycle_name, ', ') within group (order by efforts_id) as cycle_name
  from yourtable
  group by efforts_id
) c
inner join
(
  select distinct efforts_id, release_name
  from yourtable
) r
  on c.efforts_id = r.efforts_id
group by c.efforts_id, c.cycle_name

请参阅带有演示的 SQL Fiddle

于 2012-10-30T16:06:54.473 回答
2

如果您有 Oracle 11g R2,那么 LISTAGG 是首选方法:

SELECT efforts_id,
    LISTAGG(cycle_name) WITHIN GROUP(ORDER BY cycle_name),
    LISTAGG(release_name) WITHIN GROUP(ORDER BY cycle_name)
FROM MY_TABLE
GROUP BY efforts_id

如果没有,本文将展示替代方法。

于 2012-10-30T15:48:03.867 回答
0

通过WM_concat函数(GROUP BY当然还有)

SELECT efforts_id, wm_concat(cycle_name), wm_concat(release_name)
FROM MY_TABLE
GROUP BY efforts_id

嗯,刚找到这个:

请注意,WM_CONCAT记录且不受Oracle 支持,这意味着不应在生产系统中使用LISTAGG函数,它可以产生与WM_CONCAT相同的输出, Oracle已记录并支持它。

于 2012-10-30T15:42:48.680 回答