如何从一个表上的行获取值到另一个表的列

时间:2015-07-10 10:35:38

标签: sql database oracle

我有两张表,如下所示:

第一张表

   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

我真的很痴在这里的逻辑,如果我加入两个表使用 内部联接然后输出表将包含多个CustomerId ,这里不需要任何帮助。任何帮助都会非常明显。
提前完成。

3 个答案:

答案 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 :(得分: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

答案 2 :(得分: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;