力扣1083-销售分析II

表:Product

复制代码
+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| product_id   | int     |
| product_name | varchar |
| unit_price   | int     |
+--------------+---------+
Product_id 是该表的主键(具有唯一值的列)。
该表的每一行表示每种产品的名称和价格。

表:Sales

复制代码
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| seller_id   | int     |
| product_id  | int     |
| buyer_id    | int     |
| sale_date   | date    |
| quantity    | int     |
| price       | int     |
+------ ------+---------+
这个表可能有重复的行。
product_id 是 Product 表的外键(reference 列)。
buyer_id 永远不会是 NULL。
sale_date 永远不会是 NULL。
该表的每一行都包含一次销售的一些信息。

编写一个解决方案,报告那些买了 S8 而没有买 iPhone 的 买家 。注意,S8 和 iPhone 是 Product 表中显示的产品。

以 任意顺序 返回结果表。

结果格式如下所示。

示例 1:

复制代码
输入:
Product table:
+------------+--------------+------------+
| product_id | product_name | unit_price |
+------------+--------------+------------+
| 1          | S8           | 1000       |
| 2          | G4           | 800        |
| 3          | iPhone       | 1400       |
+------------+--------------+------------+
Sales table:
+-----------+------------+----------+------------+----------+-------+
| seller_id | product_id | buyer_id | sale_date  | quantity | price |
+-----------+------------+----------+------------+----------+-------+
| 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  |
+-----------+------------+----------+------------+----------+-------+
输出:
+-------------+
| buyer_id    |
+-------------+
| 1           |
+-------------+
解释:
id 为 1 的买家购买了一部 S8,但是却没有购买 iPhone,而 id 为 3 的买家却同时购买了这 2 部手机。

思路:

1、首先两个表关联;

2、case when 判断是否有卖S8和iPhone,有为1 否则为0

3、根据题目要求,"买了 S8 而没有买 iPhone 的 买家",所以sum(S8)>0 ,sum(iPhone)=0;

代码:

sql 复制代码
select 
buyer_id 
from product t1
join sales t2 on t1.product_id= t2.product_id
group by buyer_id
having sum(case when product_name = 'S8'then 1 else 0 end) > 0 
   and sum(case when product_name = 'iPhone' then 1 else 0 end) = 0
;
相关推荐
Nil2082 小时前
leetcode 118杨辉三角
算法·leetcode·职场和发展
All for pursuit.5 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode
CoderYanger9 小时前
A.每日一题:1614. 括号的最大嵌套深度
java·程序人生·算法·leetcode·面试·学习方法
杨云龙UP9 小时前
Oracle 19c 单机到单机 Active Data Guard 搭建与巡检操作手册
数据库·oracle·adg·操作指南·data guard·dg搭建
Xin7709 小时前
LeetCode 230. 二叉搜索树中第 K 小的元素(迭代中序遍历 + 栈)
leetcode
Navigator_Z10 小时前
LeetCode //C - 1283. Find the Smallest Divisor Given a Threshold
c语言·算法·leetcode
我不会起名字32211 小时前
二叉树的遍历与二叉搜索树:把递归、迭代、还原树一次讲透
数据结构·leetcode·二叉树·二叉搜索树
yi01112 小时前
Leetcode 49 用 “身份证‘‘巧解
人工智能·笔记·python·算法·leetcode·哈希表
yi01112 小时前
DAY22: LeetCode 733:图像渲染——从二维网格开始理解 DFS 和 BFS
数据结构·笔记·python·算法·leetcode·深度优先·宽度优先
Pniubi12 小时前
力扣41缺失的第一个正数(哈希表法)
算法·leetcode·职场和发展