LeetCode 1082,1083,1084 Sales Analysis

本文提供了三个SQL查询,分别用于找出最佳销售员、购买S8但未购买iPhone的买家以及仅在2019年春季售出的产品。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Create table If Not Exists Product (product_id int, product_name varchar(10), unit_price int)
Create table If Not Exists Sales (seller_id int, product_id int, buyer_id int, sale_date date, quantity int, price int)
Truncate table Product
insert into Product (product_id, product_name, unit_price) values ('1', 'S8', '1000')
insert into Product (product_id, product_name, unit_price) values ('2', 'G4', '800')
insert into Product (product_id, product_name, unit_price) values ('3', 'iPhone', '1400')
Truncate table Sales
insert into Sales (seller_id, product_id, buyer_id, sale_date, quantity, price) values ('1', '1', '1', '2019-01-21', '2', '2000')
insert into Sales (seller_id, product_id, buyer_id, sale_date, quantity, price) values ('1', '2', '2', '2019-02-17', '1', '800')
insert into Sales (seller_id, product_id, buyer_id, sale_date, quantity, price) values ('2', '2', '3', '2019-06-02', '1', '800')
insert into Sales (seller_id, product_id, buyer_id, sale_date, quantity, price) values ('3', '3', '4', '2019-05-13', '2', '2800')

 

1082. Sales Analysis I

Write an SQL query that reports the best seller by total sales price, If there is a tie, report them all.

CTE:

with cte as (
select seller_id,sum(price) as total_price
from Sales
group by seller_id
),cte2 as (
select seller_id,rank() over(order by total_price desc) as rnk
from cte
) select seller_id 
from cte2 
where rnk=1

Having

select seller_id
from Sales
group by seller_id
having sum(price)=
(
select top 1 sum(price) from sales group by seller_id order by 1 desc
)

 

1083. Sales Analysis II

Write an SQL query that reports the buyers who have bought S8 but not iPhone. Note that S8 and iPhone are products present in the Product table.

 

select distinct buyer_id
from Sales s join Product p on
s.product_id=p.product_id
where p.product_name='S8'
and buyer_id not in
(
select distinct buyer_id
from Sales s join Product p on
s.product_id=p.product_id
where p.product_name='iPhone'
)

 

Using sum:

SELECT s.buyer_id
FROM Sales AS s INNER JOIN Product AS p
ON s.product_id = p.product_id
GROUP BY s.buyer_id
HAVING SUM(CASE WHEN p.product_name = 'S8' THEN 1 ELSE 0 END) > 0
AND SUM(CASE WHEN p.product_name = 'iPhone' THEN 1 ELSE 0 END) = 0

 

1084. Sales Analysis III

Write an SQL query that reports the products that were only sold in spring 2019. That is, between 2019-01-01 and 2019-03-31 inclusive.

 

Having

select s.product_id,p.product_name
from Sales s join Product p on 
s.product_id=p.product_id
group by s.product_id,p.product_name
having max(s.sale_date)<='2019-03-31'
and min(s.sale_date)>='2019-01-01'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值