繁体   English   中英

从一列中选择电话号码成多列sql

[英]select phone numbers from one column into multiple columns sql

我有一个称为phone的表,我需要在六个单独的列中返回前三个电话号码和每种c_no的三种类型,然后再加入contacts表。 电话桌的布局是这样的,

p_no,c_no, phone, p_type

我想要的结果集是

c_no, First_Phone, First_Phone_Type, Second_Phone, Second_Phone_Type, Third_Phone, Third_Phone_Type

我尝试了以下操作,但是当我通过c_no添加组时,第二列或第三列中没有显示任何内容

select  c_no,
        (case when cp_sort = 1 and cp_status = 1 then phone end) as Phone_1,
        (case when cp_sort = 2 and cp_status = 1 then phone end) as Phone_2,
        (case when cp_sort = 3 and cp_status = 1 then phone end) as Phone_3
 from   phones cp  
 group by
         c_no

提前非常感谢你们提供的所有帮助!

您可以尝试:

select distinct c_no, 
  (select phone from phones p1 where p0.c_no = p1.c_no and cp_sort = 1) Phone_1,
  (select phone from phones p2 where p0.c_no = p2.c_no and cp_sort = 2) Phone_2,
  (select phone from phones p3 where p0.c_no = p3.c_no and cp_sort = 3) Phone_3
from phones p0;

可能需要一些优化才能在大量数据上正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM