转载:
声明:如果我侵犯了任何人的权利,请联系我,我会删除
欢迎高手来喷我
1398. 购买了产品A和产品B却没有购买产品C的顾客
链接:https://leetcode-cn.com/problems/customers-who-bought-products-a-and-b-but-not-c/solution/liang-chong-fang-shi-xi-huan-jiu-xing-by-rosieisme/
题目描述
customer_id 是这张表的主键。
customer_name 是顾客的名称。
order_id 是这张表的主键。
customer_id 是购买了名为 “product_name” 产品顾客的id。
查询结果如下例所示。
题解
select a.customer_id, a.customer_name
from Customers a join Orders b on a.customer_id = b.customer_id
group by a.customer_id
having
sum(b.product_name ='A') *sum(b.product_name='B') >0
and sum(b.product_name = 'C') = 0
SELECT
customer_id, customer_name
FROM
Customers
WHERE
customer_id NOT IN (
SELECT customer_id
FROM Orders
WHERE product_name = 'C'
) AND Customer_id IN (
SELECT customer_id
FROM Orders
WHERE product_name = 'A'
) AND Customer_id IN (
SELECT customer_id
FROM Orders
WHERE product_name = 'B'
)
ORDER BY customer_id
1596. 每位顾客最经常订购的商品
链接:https://leetcode-cn.com/problems/the-most-frequently-ordered-products-for-each-customer
题目描述
customer_id 是该表主键
该表包含所有顾客的信息
order_id 是该表主键
该表包含顾客 customer_id 的订单信息
没有顾客会在一天内订购相同的商品 多于一次
写一个 SQL 语句,找到每一个顾客最经常订购的商品。
结果表单应该有每一位至少下过一次单的顾客 customer_id , 他最经常订购的商品的 product_id 和 product_name。
返回结果 没有顺序要求。
查询结果格式如下例所示:
Alice (customer 1) 三次订购鼠标, 一次订购键盘, 所以鼠标是 Alice 最经常订购的商品.
Bob (customer 2) 一次订购键盘, 一次订购鼠标, 一次订购显示器, 所以这些都是 Bob 最经常订购的商品.
Tom (customer 3) 只两次订购显示器, 所以显示器是 Tom 最经常订购的商品.
Jerry (customer 4) 只一次订购键盘, 所以键盘是 Jerry 最经常订购的商品.
John (customer 5) 没有订购过商品, 所以我们并没有把 John 包含在结果表中.
题解
select b.customer_id, c.product_id,p.product_name
from
(
select a.customer_id, a.product_id, max(a.cnt)as maxcnt
from
(
select customer_id, product_id, count(order_id)as cnt
from orders
group by customer_id, product_id
)a
group by a.customer_id
)b
join
(
select customer_id, product_id, count(order_id) as cnt
from orders
group by customer_id, product_id
)c
on b.customer_id = c.customer_id and b.maxcnt = c.cnt
join products p on p.product_id = c.product_id
order by b.customer_id, c.product_id
1421. 净现值查询
题目描述
写一个 SQL, 找到 Queries 表中每一次查询的净现值.
结果表没有顺序要求.
查询结果的格式如下所示:
(7, 2018)的净现值不在 NPV 表中, 我们把它看作是 0.
所有其它查询的净现值都能在 NPV 表中找到.
题解
select q.id, q.year, ifnull(npv,0)as npv
from queries q left join npv n on q.id = n.id and q.year = n.year
order by q.id, q.year
# Write your MySQL query statement below
select
q.id,
q.year,
ifnull(npv,0) npv
from
Queries q
left join
NPV n using(id,year);