2017-03-17 12 views
0

私は以下のようにOracleにテーブルを持っています。一列にSQL 1つの行に2つの列の別個の出力を選択します。

私は明確な会社を選択したい
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

** ** DISTINCT **を選択する必要はありません。 UNIONはとにかに結果を重複除外します。私たちのソリューションの違いは、私がUNPIVOTを使う方法です。利益はすぐには分かりません。 UNPIVOTは基本表を1回しか読み取るのではなく、UNIONアプローチでは基本表を2回読み取る必要があり(高価なI/Oが増えます)、事実です。 – mathguy

関連する問題