简体   繁体   English

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

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

I have a table called phones which I need to return the top three phone numbers, and three types for each c_no in six separate columns and then join to the contacts table. 我有一个称为phone的表,我需要在六个单独的列中返回前三个电话号码和每种c_no的三种类型,然后再加入contacts表。 The phone table is laid out like so, 电话桌的布局是这样的,

p_no,c_no, phone, p_type

My desired result set would be, 我想要的结果集是

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

I tried the following, but it doesn't show anything in the second or third columns when I add the group by c_no 我尝试了以下操作,但是当我通过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

Thank you guys so much in advance for all the help! 提前非常感谢你们提供的所有帮助!

You could try: 您可以尝试:

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;

Might need some optimization to work well on a large set of data. 可能需要一些优化才能在大量数据上正常工作。

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

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