目录
题目
准备数据
分析数据
总结
题目
编写SQL查询以根据以下条件报告所有订单:
- 如果客户至少有一个类型为0的订单,则不要报告该客户的任何类型为1的订单。
- 否则,报告客户的所有订单。
按任意顺序返回结果表。
准备数据
Create table If Not Exists Orders (order_id int, customer_id int, order_type int)
Truncate table Orders
insert into Orders (order_id, customer_id, order_type) values ('1', '1', '0')
insert into Orders (order_id, customer_id, order_type) values ('2', '1', '0')
insert into Orders (order_id, customer_id, order_type) values ('11', '2', '0')
insert into Orders (order_id, customer_id, order_type) values ('12', '2', '1')
insert into Orders (order_id, customer_id, order_type) values ('21', '3', '1')
insert into Orders (order_id, customer_id, order_type) values ('22', '3', '0')
insert into Orders (order_id, customer_id, order_type) values ('31', '4', '1')
insert into Orders (order_id, customer_id, order_type) values ('32', '4', '1')
分析数据
第一步:使用开窗函数rank(),对customer_id组内不同的order_type生成一列排序
select order_id, customer_id, order_type, rank() over(partition by customer_id order by order_type) rn from orders;
第二步:因为组内全部相同,排序只有1,当出现不同时,就会产生排序,把组内有0有1的1排除掉
with t1 as ( select order_id, customer_id, order_type, rank() over(partition by customer_id order by order_type) rn from orders )select order_id, customer_id, order_type from t1 where rn = 1;
总结
因为本题是只将组内同时出现有0和有1的时候,删除1,所以可以进行排序,值筛选出rn=1的