将查询结果合并到单行 - Oracle

时间:2012-05-09 09:16:49

标签: oracle plsql string-aggregation

我可以在oracle中这样做吗?我有一些这样的数据:

No | Data |
===========
 1 | A    |
 1 | B    |
 1 | C    |
 1 | D    |

是否有任何查询可以产生这样的结果,??

No | Data       |
=================
 1 | A, B, C, D |

非常感谢:D

4 个答案:

答案 0 :(得分:1)

也许this page会显示您要找的内容。

答案 1 :(得分:1)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE TEST ( ID, DATA ) AS
          SELECT 1, 'A' FROM DUAL
UNION ALL SELECT 1, 'B' FROM DUAL
UNION ALL SELECT 1, 'C' FROM DUAL
UNION ALL SELECT 1, 'D' FROM DUAL
UNION ALL SELECT 2, 'E' FROM DUAL
UNION ALL SELECT 2, 'F' FROM DUAL;

查询1

SELECT ID,
       LISTAGG( DATA, ',' ) WITHIN GROUP ( ORDER BY DATA ) AS AGGREGATED_DATA
FROM   TEST
GROUP BY ID

<强> Results

| ID | AGGREGATED_DATA |
|----|-----------------|
|  1 |         A,B,C,D |
|  2 |             E,F |

答案 2 :(得分:0)

在Oracle中,我们可以使用wm_concat函数。以下是上面的查询:

SELECT no, wm_concat(data) from table group by no

参考:wm_concat

答案 3 :(得分:0)

select 
   no,
   rtrim (xmlagg (xmlelement (d, data|| ',')).extract ('//text()'), ',') data
from 
   table_name
group by 
   no
;