2015-07-10 60 views
1

专栏中,我有两个表,看起来像:

如何从一个表中的行值的其他

第一台

CustomerId CustomerName 

    110    XYZ     
    111    ABC 
    112    PQR 
    113    LMN     

二表

CustomerId   PhoneNumber 

     110    9823983298329 
     111    9996709760760 
     110    0495054905495 
     112    8394893489843 
     113    0932023090900 
     111    0930290909999 
     113    8993293288888 
     112    9828239882388 

我想要的是一个表结构类似于:

CustomerId  CustomerName  PhoneNum1    PhoneNum2 

    110    XYZ    9823983298329  0495054905495 
    111    ABC    9996709760760  0930290909999 
    112    PQR    8394893489843  9828239882388 
    113    LMN    0932023090900  8993293288888 

我真的坚持了这里的逻辑,如果我加入使用两个表 内加入然后输出表将有多个客户编号的这里没有需要,任何帮助将是非常可观的。
Thanx提前。

+0

启动[**'ALTER TABLE' **](HTTP://www.techonthenet。 com/oracle/tables/alter_table.php)和[**'INSERT INTO' **](http://www.techonthenet.com/oracle/insert.php)。 –

+0

我不能做这个没有做任何新表? –

+0

你想让结果看起来像这样吗?或实际的表? –

回答

4

这是一种枢轴;你只需要一个专栏来转动。您可以使用条件聚集和row_number()得到这样的结果:

select t1.CustomerId, t1.CustomerName, 
     max(case when seqnum = 1 then PhoneNmber end) as PhoneNmber1, 
     max(case when seqnum = 2 then PhoneNmber end) as PhoneNmber2 
from table1 t1 left join 
    (select t2.*, 
      row_number() over (partition by customerId order by customerId) as seqnum 
     from table2 t2 
    ) t2 
    on t1.CustomerId = t2.CustomerId 
group by t1.CustomerId, t1.CustomerName; 
1

使用GROUP BY找到每个客户的最小和最大的手机没有。做一个LEFT JOIN与结果:

select f.CustomerId, 
     f.CustomerName, 
     s.min_ph, 
     case when s.min_ph <> s.max_ph then s.max_ph else null end 
from firsttable f 
    left join (select CustomerId, 
        min(PhoneNumber) min_ph, 
        max(PhoneNumber) max_ph 
      from secondtable 
      group by CustomerId) s on f.CustomerId = s.CustomerId 
0

利用解析函数通过考虑看看导致

select max(CustomerId),max(PhoneNUmber),max(PhoneNUmber2),max(PhoneNUmber3) from (
select a.CustomerId,PhoneNUmber ,lead(phonenumber,1) over(partition by a.CustomerId order by phonenumber) PhoneNUmber2,lag(phonenumber,2) over(partition by a.CustomerId order by phonenumber) PhoneNUmber3 from firsttable a 
    join secoundTable b on a.CustomerId = b.CustomerId 
    order by 1 
) 
group by CustomerId; 
相关问题