Using wm_concat to concatenate rows, but in an order determined by another column

group-concatenationoracleoracle-11g-r2

Let's say I have 3 columns: p_id, description, order_by. I am trying to do the following:

I would like to concatenate the description for all like p_id values. So we are talking a group by p_id sort of thing. But then, I want the description to be concatenated in the order of the order_by column (which is an integer). So my ideal query (not-working) would look like

select p_id, wm_concat(description)
from my_table
where p_id = 12345
group by p_id
order by order_by asc

How do I concatenate rows in this fashion?

Best Answer

So the query (which would work if under 4000 bytes) is

select p_id, listagg(description, '\n') WITHIN GROUP (ORDER BY order_by)
from my_table
where p_id = 12345
group by p_id