如何在Oracle中将多行连接成一个而不创build存储过程?
如何在不创build存储过程的情况下在oracle中实现以下function?
数据集:
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
string聚合有许多方法,但最简单的是用户定义的函数。 试试这个不需要函数的方法。 作为一个说明,没有这个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;
从Oracle 11gR2开始, LISTAGG子句应该做到这一点:
SELECT question_id, LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id) FROM YOUR_TABLE GROUP BY question_id;
简单:
SELECT question_id, wm_concat(element_id) as elements FROM questions GROUP BY question_id;
对10g进行的Pesonallytesting;-)
从http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
这个OTN线程包含几种方法来进行string聚合,包括性能比较: http : //forums.oracle.com/forums/message.jspa?messageID=1819487#1819487