-
1
- #1
I really like the WM_CONCAT function in 10g as a quick way of concatenating fields. However, it has one major drawback in that there is no way of ordering the fields in the string that it returns.
So for example:
What I've discovered is that WM_CONCAT works like an analytic function in that it can take an ORDER BY clause. We can also apply count with an order by to find out how many items have been concatenated and a count without the order by to get the total number of concatenated items.
Having got this output, all we then have to do is apply a condition running_count=tot_count and we get the sorted output.
For Oracle-related work, contact me through Linked-In.
So for example:
Code:
create table test_sort (key1 number, data_val varchar2(10));
insert into test_sort values (1, 'Z');
insert into test_sort values (1, 'Y');
insert into test_sort values (1, 'X');
insert into test_sort values (2, 'B');
insert into test_sort values (2, 'A');
select key1, wm_concat(data_val)
from test_sort
group by key1;
KEY1 OUTPUT
---------- ---------------
1 Z,Y,X
2 B,A
You might prefer X,Y,Z and A,B but there is no way to guarantee this.
What I've discovered is that WM_CONCAT works like an analytic function in that it can take an ORDER BY clause. We can also apply count with an order by to find out how many items have been concatenated and a count without the order by to get the total number of concatenated items.
Code:
select key1,
wm_concat(data_val) over (partition by key1 order by data_val) as output,
count(data_val) over (partition by key1 order by data_val) as running_count,
count(data_val) over (partition by key1) as tot_count
from test_sort
KEY1 OUTPUT RUNNING_COUNT TOT_COUNT
---------- --------------- ------------- ----------
1 X 1 3
1 X,Y 2 3
1 X,Y,Z 3 3
2 A 1 2
2 A,B 2 2
Having got this output, all we then have to do is apply a condition running_count=tot_count and we get the sorted output.
Code:
select key1, output
from
(select key1, wm_concat(data_val) over (partition by key1 order by data_val) as output,
count(data_val) over (partition by key1 order by data_val) as running_count,
count(data_val) over (partition by key1) as tot_count
from test_sort)
where running_count = tot_count
KEY1 OUTPUT
---------- ---------------
1 X,Y,Z
2 A,B
For Oracle-related work, contact me through Linked-In.