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
Oracle Listagg function helps to concatenate multiple rows into a single string.
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.
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.
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 (||).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With