leetcode-SQL-1398. 购买了产品 A 和产品 B 却没有购买产品 C 的顾客

简介: leetcode-SQL-1398. 购买了产品 A 和产品 B 却没有购买产品 C 的顾客

题目

题目链接

Customers 表:

+---------------------+---------+
| Column Name         | Type    |
+---------------------+---------+
| customer_id         | int     |
| customer_name       | varchar |
+---------------------+---------+
customer_id 是这张表的主键。
customer_name 是顾客的名称。

Orders 表:

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| customer_id   | int     |
| product_name  | varchar |
+---------------+---------+
order_id 是这张表的主键。
customer_id 是购买了名为 "product_name" 产品顾客的id。

请你设计 SQL 查询来报告购买了产品 A 和产品 B 却没有购买产品 C 的顾客的 ID 和姓名( customer_id 和 customer_name ),我们将基于此结果为他们推荐产品 C 。

您返回的查询结果需要按照 customer_id 排序。

查询结果如下例所示。

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         |
+------------+--------------+---------------+
Result table:
+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
| 3           | Elizabeth     |
+-------------+---------------+
只有 customer_id 为 3 的顾客购买了产品 A 和产品 B ,却没有购买产品 C 。

解题

select
    c.customer_id,
    c.customer_name
from Customers as c
left join Orders as o
on c.customer_id=o.customer_id
group by o.customer_id
having 
    count(if(o.product_name='A',1,null))>0
    and 
    count(if(o.product_name='B',1,null))>0
    and
    count(if(o.product_name='C',1,null))=0;
相关文章
|
3月前
|
SQL
leetcode-SQL-1164. 指定日期的产品价格
leetcode-SQL-1164. 指定日期的产品价格
18 0
|
3月前
|
SQL
leetcode-SQL-1581. 进店却未进行过交易的顾客
leetcode-SQL-1581. 进店却未进行过交易的顾客
29 0
|
数据库
LeetCode(数据库)- 每个产品在不同商店的价格
LeetCode(数据库)- 每个产品在不同商店的价格
90 0
|
数据库
LeetCode(数据库)- 每位顾客最经常订购的商品
LeetCode(数据库)- 每位顾客最经常订购的商品
95 0
|
数据库
LeetCode(数据库)- 发票中的产品金额
LeetCode(数据库)- 发票中的产品金额
77 0
|
数据库
LeetCode(数据库)- 进店却未进行过交易的顾客
LeetCode(数据库)- 进店却未进行过交易的顾客
78 0
|
数据库
LeetCode(数据库)- 按月统计订单数与顾客数
LeetCode(数据库)- 按月统计订单数与顾客数
60 0
|
数据库
LeetCode(数据库)- 按日期分组销售产品
LeetCode(数据库)- 按日期分组销售产品
94 0
|
数据库
LeetCode(数据库)- 可回收且低脂的产品
LeetCode(数据库)- 可回收且低脂的产品
79 0
|
数据库
LeetCode(数据库)- 购买了产品 A 和产品 B 却没有购买产品 C 的顾客
LeetCode(数据库)- 购买了产品 A 和产品 B 却没有购买产品 C 的顾客
103 0

热门文章

最新文章