I am trying to use the LISTAGG
function in Oracle. I would like to get only the distinct values for that column. Is there a way in which I can get only the distinct values without creating a function or a procedure?
col1 col2 Created_by 1 2 Smith 1 2 John 1 3 Ajay 1 4 Ram 1 5 Jack
I need to select col1 and the LISTAGG
of col2 (column 3 is not considered). When I do that, I get something like this as the result of LISTAGG
: [2,2,3,4,5]
I need to remove the duplicate '2' here; I need only the distinct values of col2 against col1.
The simplest way to handle multiple listagg's is to use 1 WITH (subquery factor) per column containing a listagg of that column from a select distinct:
Which gives:
If you do not need a particular order of concatenated values, and the separator can be a comma, you can do:
I neded a DISTINCT version of this and got this one working out.
If the intent is to apply this transformation to multiple columns, I have extended a_horse_with_no_name's solution:
This is Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production.
I was unable to use STRAGG because there is no way to DISTINCT and ORDER.
Performance scales linearly, which is good, since I am adding all columns of interest. The above took 3 seconds for 77K rows. For just one rollup, .172 seconds. I do with there was a way to distinctify multiple columns in a table in one pass.
I implemented this stored function :
I'm sorry, but in some case (for a very big set), Oracle could return this error:
but I think this is a good point of start ;)
Do you mean something like this:
If you need more columns, something like this might be what you are looking for: