This question already has an answer here:
I saw the previous question where the table had the columns "No" and "Name", and others that grouped with numeric columns, but was unable to implement the answers provided for my case. I need to do the same thing, but with non-numeric groupings. The source table is tbl1 with these columns:
POD Name
--- -----
North Rony
North James
North Aby
South Sam
South Willy
West Mike
I need to do this aggregation:
POD Name
--- -----
North Aby,James,Rony
South Sam,Willy
West Mike
Since "POD" is non-numeric, the previous solutions by Msyma, Dinup, and chetan didn't seem to work for me.
I don't know how to make the knowledge transfer from their answers to these requirements.
An ideal query would be
SELECT POD, AGGREGATESTRING(Name)
FROM tbl1
GROUP BY POD
In the ideal example the AGGREGATESTRING doesn't sort the people's names, but I think I'll be able to insert an "ORDER BY" where needed.
I have only been able to test this on Oracle 11g R2; however, I believe that everything is also available for Oracle 10g.
There are two functions included here both of which use collections:
DBMS_LOB
package and is more verbose but, on my tests, has seemed to be much much more efficient (although I would recommend profiling it yourself to test it).SQL Fiddle
Oracle 11g R2 Schema Setup:
For this method, you will need to define a Collection to aggregate the strings into:
This function takes a string collection (and an optional delimiter) and returns a
CLOB
containing the concatenated strings - if you have a smaller dataset (as per your example) then this is probably overkill and you can replaceCLOB
withVARCHAR2
.However, if you are going to have a long string returned as a
CLOB
then it may be more efficient to use some of the functions of theDBMS_LOB
package:Your test data:
Query 1:
Results:
Query 2:
Results:
Oracle 11g has this neat function LISTAGG that is pretty much what you want, however since you are on 10g this is not available to you (unless you decide to upgrade).
If for some reason you do not wish to (or can't due to whatever reasons) upgrade to 11g, I'd suggest looking at some alternatives to LISTAGG that are available to you on 10g.
You can check out some of the proposed alternatives here
Quickly adjusted a quick adaptation of one of the proposed alternatives to match your case scenario:
But remember that this is not the actual solution as you'll have to tailor it according to your table (not the dummy DUAL table) etc...
Your solution will probably look something along the lines of:
If you want to change the delimiter you can change it from comma in this part:
The RTRIM is there just to snip off the trailing comma from the end of the concatenated string, if you are not bothered by the trailing comma you can omit the RTRIM function to conserve readability.
yet one way WM_CONCAT
string aggregation with hierarchical query