Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

pivot + removal of duplicates

742431Nov 4 2010 — edited Nov 25 2010
Hi, I am on 11gr1 and need to pivot and concatenate string values.
drop table test_a;

create table test_a (
place_id number,
place_name varchar2(30), 
tag varchar2(30),
category_name varchar2(30),
brand_name varchar2(30),
chain_name varchar2(30));

insert into test_a values (1, 'thai thai',    'asiantag',  'restaurant',  'independent', null);
insert into test_a values (2, 'mann mobilia', 'furniture', 'home-center', 'xxl', 'moebelchain');
insert into test_a values (2, 'mann mobilia', 'furniture', 'shop',        'xxl', 'moebelchain');
insert into test_a values (2, 'mann mobilia', 'office',    'home-center', 'xxl', 'moebelchain');
insert into test_a values (2, 'mann mobilia', 'office',    'shop',        'xxl', 'moebelchain');
commit;


select
  tb.place_id ,
  substr ( sys_connect_by_path( tb.tag,           ',' ) , 2 ) as tags,
  substr ( sys_connect_by_path( tb.brand_name,    ',' ) , 2 ) as brandnames,
  substr ( sys_connect_by_path( tb.chain_name,    ',' ) , 2 ) as chainnames,
  substr ( sys_connect_by_path( tb.category_name, ',' ) , 2 ) as categorynames,
  substr ( sys_connect_by_path( tb.place_name,    ',' ) , 2 ) as names
from
  ( select 
      place_id ,
      tag ,
      category_name,
      brand_name,
      chain_name,
      place_name,
      row_number() over
        ( partition by place_id
          order by tag
        )
        as indx
    from
      (test_a)
  ) tb
where
  connect_by_isleaf = 1
connect by
  indx = prior indx + 1 and
  place_id = prior place_id
start with
  indx = 1
;
output:
|1|asian                            |independent    |<null>                 |restaurant                       |my sushi                                       |
|2|furniture,furniture,office,office|xxl,xxl,xxl,xxl|chain,chain,chain,chain|home-center,shop,home-center,shop|great place,great place,great place,great place|
the select above is a good startingpoint but contains duplicates I'd like to avoid. I could write some PL/SQL script for that but would prefer to stick to plain and efficient SQL. Any idea?

This is how the output should look like:
|1|asian           |independent|<null>|restaurant      |my sushi   |
|2|furniture,office|xxl        |chain |home-center,shop|great place|
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 3 2010
Added on Nov 4 2010
13 comments
2,147 views