如何在不创建存储过程的情况下将多行连接成Oracle中的一行?

时间:2009-07-02 18:41:35

标签: sql oracle concatenation string-aggregation

如何在不创建存储过程的情况下在oracle中实现以下功能?

数据集:

question_id    element_id
1              7
1              8
2              9
3              10
3              11
3              12

期望的结果:

question_id    element_id
1              7,8
2              9
3              10,11,12

4 个答案:

答案 0 :(得分:97)

从Oracle 11gR2开始,LISTAGG子句可以解决这个问题:

SELECT question_id,
       LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id)
FROM YOUR_TABLE
GROUP BY question_id;

请注意结果字符串是否太大(例如,对于VARCHAR2超过4000个字符):从版本12cR2开始,我们可以使用ON OVERFLOW TRUNCATE/ERROR来处理此问题。

答案 1 :(得分:36)

易:

SELECT question_id, wm_concat(element_id) as elements
FROM   questions
GROUP BY question_id;

在10g上进行Pesonally测试; - )

来自http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php

答案 2 :(得分:28)

有许多方法可以进行字符串聚合,但最简单的方法是用户定义的函数。 Try this for a way that does not require a function.作为一个注释,没有这个功能就没有简单的方法。

这是没有自定义函数的最短路径:(它使用ROW_NUMBER()和SYS_CONNECT_BY_PATH函数)

SELECT questionid,
       LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
       KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM   (SELECT questionid,
               elementid,
               ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
               ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
        FROM   emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;

答案 3 :(得分:2)

此OTN线程包含几种进行字符串聚合的方法,包括性能比较:http://forums.oracle.com/forums/message.jspa?messageID=1819487#1819487