MySQL高阶2084-为订单类型为0的客户删除类型为1的订单

目录

题目

准备数据

分析数据

总结


题目

编写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的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值