Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can multiple rows be concatenated into one in Oracle without creating a stored procedure? [duplicate]

How can I achieve the following in oracle without creating a stored procedure?

Data Set:

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

Desired Result:

question_id    element_id 1              7,8 2              9 3              10,11,12 
like image 208
Dan Polites Avatar asked Jul 02 '09 18:07

Dan Polites


People also ask

How do I concatenate multiple rows into a single string in Oracle?

Oracle Listagg function helps to concatenate multiple rows into a single string.

How do I merge multiple rows in one row in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

Can you insert multiple rows in Oracle?

The Oracle INSERT ALL statement is used to add multiple rows with a single INSERT statement. The rows can be inserted into one table or multiple tables using only one SQL command.

How do I concatenate more than two columns in Oracle?

Oracle String concatenation allows you to append one string to the end of another string. To display the contents of two columns or more under the name of a single column, you can use the double pipe concatenation operator (||).


1 Answers

From Oracle 11gR2, the LISTAGG clause should do the trick:

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

Beware if the resulting string is too big (more than 4000 chars for a VARCHAR2, for instance): from version 12cR2, we can use ON OVERFLOW TRUNCATE/ERROR to deal with this issue.

like image 167
Emmanuel Avatar answered Sep 20 '22 20:09

Emmanuel