我们有以下要求
我需要处于活动状态的customer_name,并且indore,Mumbai中的attribute_name = City和attribute_value,结果应返回小于等于2的计数
这意味着从印多尔(Indore)的结果中我应该得到3的2个结果,对于孟买,我应该从1中得到1的结果。
我尝试了以下两种方法,但为印多尔和孟买的客户获取了所有行 客户表格具有以下详细信息 customer_details 表具有以下详细信息customer_id customer_name customer_Status
------------------------------------------
1 ABC Active
2 XYZ Active
3 PQR NA
4 ABCD Active
4 ABCDE Active
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;
答案 0 :(得分:0)
请尝试这种方式。
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
答案 1 :(得分:0)
这种设计会扼杀您希望吸引客户的任何性能。我要做的第一件事是将customer_details表和phone_number,城市和国家/地区列删除到customers表中。缺乏我将创建一个将客户连接到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;