问题描述
我有一张桌子:我想让它加入到基本桌子客户的电话(customer_id为PK)。加入后,我得到重复的行。我需要根据描述列上的查询将号码列分为3个单独的列,分别是电话号码,传真号码和手机号码。
电话:
这是我尝试过的
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
但是要避免将它们放在多行中
我只希望最后只包含所有这些值的一行。 结果就是我想要的:
预先感谢
解决方法
这是非常快捷和肮脏的,但可能正是您想要的。 。 。假设您要查找的字段每次出现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'