力扣1083(MySQL)-销售分析Ⅱ(简单)
题目:
编写一个 SQL 查询,查询购买了 S8 手机却没有购买 iPhone 的买家。注意这里 S8 和 iPhone 是 Product 表中的产品。
查询结果格式如下图表示:
Product table:
Sales table:
Result table:
id 为 1 的买家购买了一部 S8,但是却没有购买 iPhone,而 id 为 3 的买家却同时购买了这 2 部手机。
建表语句:
1 DROP table if exists Product_1083, Sales_1083; 2 Create table If Not Exists Product_1083 (product_id int, product_name varchar(10), unit_price int); 3 Create table If Not Exists Sales_1083 (seller_id int, product_id int, buyer_id int, sale_date date, quantity int, price int); 4 Truncate table Product_1083; 5 insert into Product_1083 (product_id, product_name, unit_price) values ('1', 'S8', '1000'),('2', 'G4', '800'),('3', 'iPhone', '1400'); 6 Truncate table Sales_1083; 7 insert into Sales_1083 (seller_id, product_id, buyer_id, sale_date, quantity, price) values ('1', '1', '1', '2019-01-21', '2', '2000'),('1', '2', '2', '2019-02-17', '1', '800'),('2', '1', '3', '2019-06-02', '1', '800'),('3', '3', '3', '2019-05-13', '2', '2800');
解题思路:
方法一:sum()
- 先将两个表通过 product_id 进行联结;
- 再以buyer_id进行分组,筛选出购买 S8 且没有购买 iPhone 的买家。
1 select buyer_id 2 from ( 3 select product_name,b.product_id,buyer_id 4 from product_1083 a 5 right join sales_1083 b 6 on a.product_id = b.product_id 7 ) as temp 8 group by temp.buyer_id 9 having sum(temp.product_name = 'S8') >= 1 and sum(temp.product_name = 'iPhone') = 0;
方法二:
- 先找出购买了 iPhone 的 buyer_id
- 然后再筛选出购买了S8但是buyer_id没在第一步查询出的结果里的数据。
1 SELECT 2 buyer_id 3 FROM 4 product_1083 5 JOIN sales_1083 USING ( product_id ) 6 WHERE 7 product_name = 'S8' 8 AND buyer_id NOT IN ( SELECT buyer_id FROM product_1083 JOIN sales_1083 USING ( product_id ) WHERE a.product_name = 'iPhone' )
标签:
MySQL
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2022-04-10 selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH.的解决办法
2022-04-10 力扣442(java)-数组中重复的数据(中等)