2017-03-17 45 views
0

我在Oracle中有一张表,如下所示。SQL在一行中选择不同的两列输出

COMPANY BUSINESS CONTACT1   CONTACT2 
ABC  CL  [email protected] [email protected] 
ABC  YM  [email protected] [email protected] 
ABC  ZF  [email protected] [email protected] 
XYZ  CL  [email protected] [email protected] 
XYZ  YM  [email protected] [email protected] 
GEF  CL  [email protected] [email protected] 

我想通过分隔单列选择不同的公司和CONTACT1和CONTACT2,如下

OUTPUT:

COMPANY  CONTACT 
ABC   [email protected],[email protected],[email protected],[email protected] 
XYZ   [email protected],[email protected],[email protected] 
GEF   [email protected],[email protected] 

回答

3
with 
    inputs (company, business, contact1, contact2) as (
     select 'ABC', 'CL', '[email protected]', '[email protected]' from dual union all 
     select 'ABC', 'YM', '[email protected]', '[email protected]' from dual union all 
     select 'ABC', 'ZF', '[email protected]', '[email protected]' from dual union all 
     select 'XYZ', 'CL', '[email protected]', '[email protected]' from dual union all 
     select 'XYZ', 'YM', '[email protected]', '[email protected]' from dual union all 
     select 'GEF', 'CL', '[email protected]', '[email protected]' 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  [email protected],[email protected],[email protected],[email protected] 
GEF  [email protected],[email protected] 
XYZ  [email protected],[email protected],[email protected] 
+0

是辉煌! – hackvan

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 
+1

请注意,您不需要SELECT ** DISTINCT **;无论如何,UNION都会重复删除结果。我们的解决方案之间的差异是我使用UNPIVOT的方式。好处可能不会立即显现;事实上,UNPIVOT只能读取一次基表,而UNION方法需要读取两次基表(导致更多的I/O,这很昂贵)。 – mathguy

相关问题