目录
一、力扣原题链接
1532. 最近的三笔订单
二、题目描述
三、建表语句
drop table if exists Customers;
drop table if exists orders;
Create table If Not Exists Customers (customer_id int, name varchar(10));
Create table If Not Exists Orders (order_id int, order_date date, customer_id int, cost int);
Truncate table Customers;
insert into Customers (customer_id, name) values ('1', 'Winston');
insert into Customers (customer_id, name) values ('2', 'Jonathan');
insert into Customers (customer_id, name) values ('3', 'Annabelle');
insert into Customers (customer_id, name) values ('4', 'Marwan');
insert into Customers (customer_id, name) values ('5', 'Khaled');
Truncate table Orders;
insert into Orders (order_id, order_date, customer_id, cost) values ('1', '2020-07-31', '1', '30');
insert into Orders (order_id, order_date, customer_id, cost) values ('2', '2020-7-30', '2', '40');
insert into Orders (order_id, order_date, customer_id, cost) values ('3', '2020-07-31', '3', '70');
insert into Orders (order_id, order_date, customer_id, cost) values ('4', '2020-07-29', '4', '100');
insert into Orders (order_id, order_date, customer_id, cost) values ('5', '2020-06-10', '1', '1010');
insert into Orders (order_id, order_date, customer_id, cost) values ('6', '2020-08-01', '2', '102');
insert into Orders (order_id, order_date, customer_id, cost) values ('7', '2020-08-01', '3', '111');
insert into Orders (order_id, order_date, customer_id, cost) values ('8', '2020-08-03', '1', '99');
insert into Orders (order_id, order_date, customer_id, cost) values ('9', '2020-08-07', '2', '32');
insert into Orders (order_id, order_date, customer_id, cost) values ('10', '2020-07-15', '1', '2');
四、题目分析
-- 1、排名,按照用户分组,日期倒序排列排名
-- 2、关联客户表带出客户名称
-- 3、筛选最近3笔订单
图就省略了。。。
五、SQL解答
with t1 as (
select
order_id, order_date, customer_id, cost,
-- 1、排名,按照用户分组,日期倒序排列排名
dense_rank() over (partition by customer_id order by order_date desc) dr
from orders
)
select
name as customer_name,
c.customer_id,
order_id,
order_date
from t1
-- 2、关联客户表带出客户名称
join customers c on c.customer_id = t1.customer_id
-- 3、筛选最近3笔订单
where dr <= 3
order by customer_name,customer_id,order_date desc
;
六、最终答案
with t1 as (
select
order_id, order_date, customer_id, cost,
-- 1、排名,按照用户分组,日期倒序排列排名
dense_rank() over (partition by customer_id order by order_date desc) dr
from orders
)
select
name as customer_name,
c.customer_id,
order_id,
order_date
from t1
-- 2、关联客户表带出客户名称
join customers c on c.customer_id = t1.customer_id
-- 3、筛选最近3笔订单
where dr <= 3
order by customer_name,customer_id,order_date desc
;