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

这个问题在这里已有答案:

  • SQL查询以串联Oracle中多个行的列值                                     11个答案

如何在不创建存储过程的情况下在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个解决方案
104 votes

在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来处理此问题。

Emmanuel answered 2019-11-15T11:35:41Z
37 votes

简单:

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

经过10g亲自测试;-)

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

hegemon answered 2019-11-15T11:36:13Z
28 votes

有很多方法可以进行字符串聚合,但是最简单的方法是用户定义函数。 尝试此操作不需要某种功能。 注意,没有该功能没有简单的方法。

这是没有自定义函数的最短路由:(它使用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;
jle answered 2019-11-15T11:35:11Z
2 votes

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

Rob van Wijk answered 2019-11-15T11:36:38Z
translate from https://stackoverflow.com:/questions/1076011/how-can-multiple-rows-be-concatenated-into-one-in-oracle-without-creating-a-stor