SQL在一行中选择两列的不同输出

时间:2017-03-17 18:50:19

标签: sql oracle

我在Oracle中有一个表格,如下所示。

COMPANY  BUSINESS   CONTACT1          CONTACT2
ABC        CL       email1@abc.com    email2@abc.com
ABC        YM       email1@abc.com    email3@abc.com
ABC        ZF       email4@abc.com    email1@abc.com
XYZ        CL       email1@xyz.com    email2@xyz.com
XYZ        YM       email3@xyz.com    email1@xyz.com
GEF        CL       email1@gef.com    email2@gef.com

我想在单行中选择不同的COMPANY和CONTACT1和CONTACT2,如下所示

输出:

COMPANY      CONTACT
ABC          email1@abc.com,email2@abc.com,email3@abc.com,email4@abc.com
XYZ          email1@xyz.com,email2@xyz.com,email3@xyz.com
GEF          email1@gef.com,email2@gef.com

2 个答案:

答案 0 :(得分:3)

with
     inputs ( company, business, contact1, contact2 ) as (
       select 'ABC', 'CL', 'email1@abc.com', 'email2@abc.com' from dual union all
       select 'ABC', 'YM', 'email1@abc.com', 'email3@abc.com' from dual union all
       select 'ABC', 'ZF', 'email4@abc.com', 'email1@abc.com' from dual union all
       select 'XYZ', 'CL', 'email1@xyz.com', 'email2@xyz.com' from dual union all
       select 'XYZ', 'YM', 'email3@xyz.com', 'email1@xyz.com' from dual union all
       select 'GEF', 'CL', 'email1@gef.com', 'email2@gef.com' from dual
     )
-- end of test data; SQL solution begins below this line
select company, listagg(email, ',') within group (order by email) as email_list
from   (
         select distinct company, email
         from   inputs
         unpivot (email for col in (contact1, contact2))
       )
group by company
;

COMPANY   EMAIL_LIST
-------   --------------------------------------------------------
ABC       email1@abc.com,email2@abc.com,email3@abc.com,email4@abc.com
GEF       email1@gef.com,email2@gef.com
XYZ       email1@xyz.com,email2@xyz.com,email3@xyz.com

答案 1 :(得分:2)

SELECT company , listagg(emails, ',') WITHIN GROUP (ORDER BY emails) as emails
FROM (
    SELECT DISTINCT company, contact1 AS emails FROM yourtable
    UNION 
    SELECT DISTINCT company, contact2  AS emails  FROM yourtable
) tt
GROUP BY company