SQL左联接避免空条目

问题描述

我有一张桌子:我想让它加入到基本桌子客户的电话(customer_id为PK)。加入后,我得到重复的行。我需要根据描述列上的查询将号码列分为3个单独的列,分别是电话号码,传真号码和手机号码。

电话:

enter image description here

这是我尝试过的

select cust.customer_id,customer_phone_id,CASE
    WHEN description like '%OFFICE%' or description like '%PHONE%' THEN number
    ELSE null
END AS [Phone Number],CASE
    WHEN description like '%FAX%' THEN number
    ELSE null
END AS [Fax Number],CASE
    WHEN description like '%CELL%' or description like '%MOBILE%' THEN number
    ELSE null
END AS [Cell Number] 
from customer cust 
left join customer_phone ph on cust.customer_id=ph.customer_id and ph.number is not null
order by customer_phone_id desc

但是要避免将它们放在多行中

enter image description here

我只希望最后只包含所有这些值的一行。 结果就是我想要的:

enter image description here

预先感谢

解决方法

这是非常快捷和肮脏的,但可能正是您想要的。 。 。假设您要查找的字段每次出现1个,它将把所有内容“折叠”成一行。

对于customer_phone_id,我正在砍下customer_phone_id字段末尾的数字,因为我们知道下划线的customer_id的长度+ 1。





select 
    cust.customer_id,CONCAT(cust.customer_id,'_',MAX(RIGHT(customer_phone_id,LEN(customer_phone_id)-1-LEN(customer_id)))) customer_phone_id,MAX(CASE WHEN description like '%OFFICE%' or description like '%PHONE%' THEN number
        ELSE null END) AS [Phone Number],MAX(CASE WHEN description like '%FAX%' THEN number
        ELSE null END) AS [Fax Number],MAX(CASE WHEN description like '%CELL%' or description like '%MOBILE%' THEN number
        ELSE null END) AS [Cell Number] 
from 
    customer cust 
    left join customer_phone ph on cust.customer_id=ph.customer_id and ph.number is not null
group by
    cust.customer_id
order by 
    customer_phone_id desc
,

您需要条件聚合:

select 
    c.customer_id,max(cp.customer_phone_id) customer_phone_id,max(case when cp.description like '%OFFICE%' or cp.description like '%PHONE%' then cp.number end) as phone_number,max(case when cp.description like '%FAX%' then cp.number end) as fax_number,max(case when cp.description like '%CELL%' or cp.description like '%MOBILE%' then cp.number end) as cell_number
from customer c
left join customer_phone cp on c.customer_id = cp.customer_id 
group by c.customer_id
order by customer_phone_id desc
,
select
   cust.customer_id,ph_cell.customer,''phone_number,ph_fax.number Fax_number,ph_cell.number Cell_number 
from
   customer cust 
   left join
      phone ph_cell 
      on cust.customer_id = ph_cell.customer 
      and ph_cell.descriptions = 'cell' 
   left join
      phone ph_fax 
      on cust.customer_id = ph_fax.customer 
      and ph_fax.descriptions = 'fax'

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...