返回介绍

solution / 1300-1399 / 1398.Customers Who Bought Products A and B but Not C / README_EN

发布于 2024-06-17 01:03:20 字数 3417 浏览 0 评论 0 收藏 0

1398. Customers Who Bought Products A and B but Not C

中文文档

Description

Table: Customers

+---------------------+---------+
| Column Name     | Type  |
+---------------------+---------+
| customer_id     | int   |
| customer_name     | varchar |
+---------------------+---------+
customer_id is the column with unique values for this table.
customer_name is the name of the customer.

 

Table: Orders

+---------------+---------+
| Column Name   | Type  |
+---------------+---------+
| order_id    | int   |
| customer_id   | int   |
| product_name  | varchar |
+---------------+---------+
order_id is the column with unique values for this table.
customer_id is the id of the customer who bought the product "product_name".

 

Write a solution to report the customer_id and customer_name of customers who bought products "A", "B" but did not buy the product "C" since we want to recommend them to purchase this product.

Return the result table ordered by customer_id.

The result format is in the following example.

 

Example 1:

Input: 
Customers table:
+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
| 1       | Daniel    |
| 2       | Diana     |
| 3       | Elizabeth   |
| 4       | Jhon      |
+-------------+---------------+
Orders table:
+------------+--------------+---------------+
| order_id   | customer_id  | product_name  |
+------------+--------------+---------------+
| 10     |   1    |   A     |
| 20     |   1    |   B     |
| 30     |   1    |   D     |
| 40     |   1    |   C     |
| 50     |   2    |   A     |
| 60     |   3    |   A     |
| 70     |   3    |   B     |
| 80     |   3    |   D     |
| 90     |   4    |   C     |
+------------+--------------+---------------+
Output: 
+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
| 3       | Elizabeth   |
+-------------+---------------+
Explanation: Only the customer_id with id 3 bought the product A and B but not the product C.

Solutions

Solution 1: LEFT JOIN + GROUP BY + HAVING

We can use LEFT JOIN to join the Customers table and the Orders table, then group them by customer_id, and finally filter out the customers who have purchased products A and B but not product C.

# Write your MySQL query statement below
SELECT customer_id, customer_name
FROM
  Customers
  LEFT JOIN Orders USING (customer_id)
GROUP BY 1
HAVING SUM(product_name = 'A') > 0 AND SUM(product_name = 'B') > 0 AND SUM(product_name = 'C') = 0
ORDER BY 1;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文