sql找到购买相同品牌产品的客户,每个品牌至少有2种产品

ttcibm8c  于 2021-08-01  发布在  Java
关注(0)|答案(3)|浏览(508)

我有两张table:

Sales
columns:  (Sales_id, Date, Customer_id, Product_id, Purchase_amount):
Product 
columns:  (Product_id, Product_Name, Brand_id,Brand_name)

我必须写一个查询来找到购买“x”和“y”品牌(两者都有)以及每个品牌至少2种产品的客户。以下查询是否正确?有什么建议的改变吗?

SELECT S.Customer_id "Customer ID"
FROM Sales S LEFT JOIN Product P
ON S.Product_id = P.Product_id
AND P.Brand_Name IN ('X','Y')
GROUP BY S.Customer_id
HAVING COUNT(DISTINCT S.Product_id)>=2 -----at least 2 products in each brand
 AND COUNT(S.Customer_id) =2 ---------------customers who bought both brands

任何帮助都将不胜感激。提前谢谢

7ajki6be

7ajki6be1#

使用 COUNT() 窗口功能统计每个客户购买的不同品牌的数量和每个品牌的不同产品的数量。
然后过滤掉那些没有同时购买品牌和服务的顾客 GROUP BY 客户有 HAVING 筛选出每个品牌至少有两种产品没有购买的顾客的条款。
你的加入也应该是一个 INNER 加入而不是加入 LEFT 加入。

select t.customer_id "Customer ID" 
from (
  select s.customer_id,
    count(distinct p.brand_id) over (partition by s.customer_id) brands_counter,
    count(distinct p.product_id) over (partition by s.customer_id, p.brand_id) products_counter
  from sales s inner join product p
  on p.product_id = s.product_id
  where p.brand_name in ('X', 'Y')
) t
where t.brands_counter = 2
group by t.customer_id
having min(t.products_counter) >= 2
xyhw6mcr

xyhw6mcr2#

从现有查询开始,可以使用以下命令 HAVING 条款:

HAVING 
    AND COUNT(DISTINCT CASE WHEN p.brand_name = 'X' then S.product_id end) >= 2
    AND COUNT(DISTINCT CASE WHEN p.brand_name = 'Y' then S.product_id end) >= 2

这样可以确保客户在两个品牌中至少购买两种产品。这隐含地保证了它在这两个品牌下了订单,因此不需要额外的逻辑。
你也可以用 MIN() 以及 MAX() :

HAVING 
    AND MIN(CASE WHEN p.brand_name = 'X' THEN S.product_id END)
        <> MAX(CASE WHEN p.brand_name = 'X' then S.product_id end)
    AND MIN(CASE WHEN p.brand_name = 'Y' THEN S.product_id END)
        <> MAX(CASE WHEN p.brand_name = 'Y' then S.product_id end)
xuo3flqw

xuo3flqw3#

可以使用两个聚合级别:

SELECT Customer_id
FROM (SELECT S.Customer_id, S.Brand_Name, COUNT(DISTINCT S.Product_Id) as num_products
      FROM Sales S LEFT JOIN
           Product P
           ON S.Product_id = P.Product_id
      WHERE P.Brand_Name IN ('X', 'Y')
      GROUP BY S.Customer_id, S.Product_Id
     ) s
GROUP BY Customer_Id
HAVING COUNT(*) = 2 AND MIN(num_products) >= 2;

相关问题