Необходимо идентифицировать PhoneNumber по категориям для идентификаторов клиентов или по рангу - PullRequest
0 голосов
/ 27 февраля 2020

Я пытался выяснить это за последние несколько дней, но все еще безуспешно. Я пытался найти ответ, но не уверен, правильно ли я формулирую вопрос, поэтому я надеюсь, что поставлю его здесь в надежде, что один из вас, замечательные люди, сможет помочь!

У меня есть таблица в PostGres Db, в которой хранятся все номера телефонов наших клиентов по их идентификатору и типу (IE Дом, Работа, Сотовый, День, Вечер и т. Д. c ...). Мне нужно вытащить эти телефонные номера и поместить их в 1 из трех столбцов, называемых home_phone, work_phone или cell_phone, в зависимости от типа столбца. Я подумал «просто! Я просто буду использовать оператор case!», Но проблема, с которой я столкнулся, заключается в том, что столбец типа имеет произвольную форму, и мой последний запрос должен быть автоматизирован, поэтому я не могу постоянно обновлять свои операторы case до добавьте любой новый «случайный» тип, который может прийти, и также нет гарантии, что у клиента будет телефонный номер, который подпадает под любую из трех категорий.

Мне как-то нужно иметь возможность уронить телефон номер в мои последние столбцы дома / работы / ячейки, и классифицировать их соответствующим образом, если у меня есть правильный «тип», НО, если у меня нет правильного «типа», то мне все еще нужно, чтобы эти номера телефонов в 1 из трех колонны.

Я попытался выяснить кое-что на основе RANK (), которое в принципе работало бы следующим образом: IF (type = 'home' затем phone_number ELSE SELECT phone_number где RANK () = MAX (RANK ())) AS home_phone , ЕСЛИ (type = 'cell' затем номер_телефона ELSE SELECT номер_телефона где RANK () = MAX (RANK ()) - 1) AS cell_phone, et c ...

Но я нигде не смог добраться с этим, и, честно говоря, я даже не думаю, что это правильно и ведет меня по неверному пути.

Вероятно, уместно сказать, что у меня есть доступ только для чтения.

Любой Помощь будет принята с благодарностью!

Мой текущий код:

select customer_id
,string_agg(home_phone,'|' order by customer_id) as home_phone
,string_agg(cell_phone,'|' order by customer_id) as cell_phone
,string_agg(work_phone,'|' order by customer_id) as work_phone
from(
select 
customer_id
,case when type in ('Home', 'phone') then phone_number end as home_phone
,case when type in ('cellphone', 'Cell', 'Mobile') then phone_number end as cell_phone
,case when type in ('Work') then phone_number end as work_phone
from reporting_data.lead_customer_phone_number
order by customer_id
) zzz
group by customer_id

1 Ответ

0 голосов
/ 03 марта 2020

достигнуто с помощью ряда операторов CASE. Код ниже на случай, если кто-то столкнется с подобной проблемой.

select lcph.customer_id,
              case 
                     when (phones.home_phone is not null) then phones.home_phone
                     when (phones.Other_1 is not null) then phones.Other_1
                     when (phones.Other_2 is not null) then phones.Other_2      --should never occur
                     when (phones.Other_3 is not null) then phones.Other_3      --should never occur
              end as home_phone,

              case 
                     when (phones.cell_phone is not null) then phones.cell_phone
                     when (phones.cell_phone is null and phones.home_phone is not null and phones.Other_1 is not null) then phones.Other_1
                     when (phones.Other_2 is not null) then phones.Other_2
                     when (phones.Other_3 is not null) then phones.Other_3      --should never occur
              end as cell_phone,

              case 
                     when (phones.work_phone is not null) then phones.work_phone
                     when (phones.work_phone is null and phones.home_phone is not null and phones.cell_phone is not null and phones.Other_1 is not null) then phones.Other_1
                     when (phones.work_phone is null and (phones.home_phone is not null or phones.cell_phone is not null) and phones.Other_2 is not null) then phones.Other_2
                     when (phones.Other_3 is not null) then phones.Other_3
              end as work_phone

  from reporting_data.lead_customer_phone_number lcph
  left join (
              -- simulate a pivot to create a row of phone numbers for each customer id
              select customer_id,
                           MAX(home_phone) as home_phone,
                           MAX(cell_phone) as cell_phone,
                           MAX(work_phone) as work_phone,
                           MAX(Other_1) as Other_1,
                           MAX(Other_2) as Other_2,
                           MAX(Other_3) as Other_3
              from (
                     -- extract out just the phone numbers we want to use
                     select a.customer_id,
                                  case when (phonetype='HOME' and level=1) then a.parsephone end as home_phone,
                                  case when (phonetype='CELL' and level=1) then a.parsephone end as cell_phone,
                                  case when (phonetype='WORK' and level=1) then a.parsephone end as work_phone,
                                  case when (phonetype='OTHER' and a.level = 1) then a.parsephone end as Other_1,
                                  case when (phonetype='OTHER' and a.level = 2) then a.parsephone end as Other_2,
                                  case when (phonetype='OTHER' and a.level = 3) then a.parsephone end as Other_3  
                     from (
                           -- Take all the lead phone numbers and group and number within the groups
                           select customer_id,
                                         phonetype,
                                         parsephone,
                                         row_number() over (partition by customer_id, phonetype  order by parsephone) as Level 
                           from (
                                  -- because duplicate data was found, filter out the dups first
                                  select distinct     customer_id,
                                                              case upper(type)
                                                                     when 'HOME' then 'HOME'
                                                                     when 'PHONE' then 'HOME'
                                                                     when 'CELLPHONE' then 'CELL'
                                                                     when 'CELL' then 'CELL'
                                                                     when 'MOBILE' then 'CELL'
                                                                     when 'WORK' then 'WORK'
                                                                     else 'OTHER'
                                                              end as phonetype,
                                                              regexp_replace(phone_number, '[^0-9]*', '', 'g') as parsephone,
                                                              phone_number as rawphone
                                                  from reporting_data.lead_customer_phone_number  
                                  ) ph
                           ) a
                     ) b
              group by customer_id
              ) phones on lcph.customer_id=phones.customer_id 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...