Требовать результат с несколькими клиентами вместе с названием города - PullRequest
0 голосов
/ 27 февраля 2020

у нас есть следующее требование

Мне нужно имя_пользователя, которое находится в Активном статусе и имя_атрибута = Город и значение атрибута в (Индор, Мумбаи), и результат должен возвращать число меньше, чем = 2

Это означает, что из результата для Индора я должен получить 2 результата из 3, а для Мумбаи я должен получить 1 из 1.

Я пробовал ниже 2 способа, но получил все строки для клиентов, которые находятся в город Индаур и Мумбаи

Таблица клиентов содержит ниже детали

customer_id customer_name customer_Status
------------------------------------------
1           ABC            Active
2           XYZ            Active
3           PQR            NA
4           ABCD           Active
4           ABCDE          Active

customer_details В таблице ниже указаны детали

customer_id  attribute_name attribute_value
------------------------------------------
1            City            Indore
1            Phone Number    9100000000
1            Country         India
2            City            Mumbai
2            Phone Number    9100000001
2            Country         India
3            City            Delhi
3            Phone Number    9100000002
3            Country         India
4            City            Mumbai
4            Phone Number    9100000003
4            Country         India
5            City            Mumbai
5            Phone Number    9100000004
5            Country         India

Код : -

select  attribute_value, r.customer_name from customer_details res
join lateral (
    select customer_name from Customer_table 
    where res.customer_id=customer_id     
    and customer_Status= 'Active'
    limit 2
) r on true
where attribute_name= 'City' and attribute_value in ('Indore','Mumbai');

Код: -

SELECT s.customer_name,attribute_value
FROM  (
   SELECT *, row_number() OVER (PARTITION BY customer_id ) AS rn
   FROM   customer_details
   WHERE   attribute_name= 'City' and attribute_value in ('Indore','Mumbai')
) e
JOIN   Customer_table s USING (customer_id)
WHERE  rn <= 2
and and customer_Status= 'Active'
ORDER  BY customer_id, e.rn;

Ответы [ 2 ]

0 голосов
/ 28 февраля 2020

Этот дизайн убьет любую производительность, которую вы надеетесь получить от клиентов. Первым делом я бы добавил таблицу customer_details и столбцы phone_number, city и country в таблицу клиентов. Не имея этого, я бы создал представление, объединяющее клиентов с customer_details со всеми столбцами в представлении.

create view Customer_Standard as 
    select c.cust_id, c.name, c.status, ph.attribute_value phone_number, ct.attribute_value city, cn.attribute_value country
      from customers c
      left join  customer_details ph on (ph.cust_id = c.cust_id and ph.attribute_name = 'Phone Number')
      left join  customer_details ct on (ct.cust_id = c.cust_id and ct.attribute_name = 'City')
      left join  customer_details cn on (cn.cust_id = c.cust_id and cn.attribute_name = 'Country') ; 

Тогда желаемым запросом станет:

select cust_id, name, status, phone_number, city, country
  from (select cs.*, row_number() over (partition by city order by cust_id) rn
          from Customer_Standard cs
       ) cust
 where city in ('Indore','Mumbai')
   and rn<3;
0 голосов
/ 27 февраля 2020

Пожалуйста, попробуйте этот способ.

select customer_name,attribute_value from (
select ct.customer_name,attribute_value,row_number() OVER (PARTITION BY attribute_value ) AS rn
from customer_table ct ,customer_details cd
where ct.customer_status = 'Active' and ct.customer_id = cd.customer_id
and attribute_name='City' and attribute_value in('Indore','Mumbai')
) as t
where rn <= 2
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...