1. 程式人生 > >oracle 中將多行合併成一行的sql語句

oracle 中將多行合併成一行的sql語句

1、使用LISTAGG 函式

select  LISTAGG(f.c_customerrole,'|') within group(order by f.c_customerrole) as customerrole  FROM TCUSTOMER_ROLE_RELATION f where f.c_customercode = ‘1001’;

1、select --customercode,

       translate(ltrim(customername, '|'), '*|', '*|') researcherlist
  from (select row_number() over(partition by customercode order by customercode, lvl desc) rn,
               customercode,
               customername
          from (select customercode,
                       level lvl,
                       sys_connect_by_path(customername, '|') customername
                  from (select f.c_customercode customercode,
                               td.dict_item_name customername,
                               row_number() over(partition by f.c_customercode order by f.c_customercode) x
                          from tcustomer_role_relation f,
                               tsys_dict_item          td,
                               tcustomer_info          t
                         where td.dict_entry_code = 'CUSTOMER_ROLE'
                           and f.c_customerrole = td.dict_item_code
                           and t.c_customercode = '24671'
                           and t.c_customercode = f.c_customercode
                         order by td.dict_item_name) a
                connect by customercode = prior customercode
                       and x - 1 = prior x))

 where rn = 1;

2、select username,
       id,
       translate(ltrim(subject, '/'), '*/', '*|') as subject,
       translate(ltrim(score, '/'), '*/', '*|') as score
  from (select row_number() over(partition by username, id order by username, id, lvl desc) as rn,
               username,
               id,
               subject,
               score
          from (select username,
                       id,
                       level lvl,
                       sys_connect_by_path(subject, '/') as subject,
                       sys_connect_by_path(score, '/') as score
                  from (select username,
                               id,
                               subject,
                               score,
                               row_number() over(partition by username, id order by username, id) as num
                          from studentscores
                         order by username, id)
                connect by username = prior username
                       and id = prior id
                       and num - 1 = prior num))
 where rn = 1;