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

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

我有两张table:

  1. Sales
  2. columns: (Sales_id, Date, Customer_id, Product_id, Purchase_amount):
  3. Product
  4. columns: (Product_id, Product_Name, Brand_id,Brand_name)

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

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

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

7ajki6be

7ajki6be1#

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

  1. select t.customer_id "Customer ID"
  2. from (
  3. select s.customer_id,
  4. count(distinct p.brand_id) over (partition by s.customer_id) brands_counter,
  5. count(distinct p.product_id) over (partition by s.customer_id, p.brand_id) products_counter
  6. from sales s inner join product p
  7. on p.product_id = s.product_id
  8. where p.brand_name in ('X', 'Y')
  9. ) t
  10. where t.brands_counter = 2
  11. group by t.customer_id
  12. having min(t.products_counter) >= 2
xyhw6mcr

xyhw6mcr2#

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

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

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

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

xuo3flqw3#

可以使用两个聚合级别:

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

相关问题