2084. 为订单类型为 0 的客户删除类型为 1 的订单

SQL架构

活动表: Orders

+-------------+------+
| Column Name | Type |
+-------------+------+
| order_id    | int  | 
| customer_id | int  |
| order_type  | int  | 
+-------------+------+
order_id是此表的主键列。
此表的每一行都表示订单的ID、订购该订单的客户的ID以及订单类型。
订单可以是类型0或类型1。

编写SQL查询以根据以下条件报告所有订单:

  • 如果客户至少有一个类型为0的订单,则不要报告该客户的任何类型为1的订单。
  • 否则,报告客户的所有订单。

按任意顺序返回结果表。

查询结果格式如下例所示。

示例 1:

输入: 
Orders table:
+----------+-------------+------------+
| order_id | customer_id | order_type |
+----------+-------------+------------+
| 1        | 1           | 0          |
| 2        | 1           | 0          |
| 11       | 2           | 0          |
| 12       | 2           | 1          |
| 21       | 3           | 1          |
| 22       | 3           | 0          |
| 31       | 4           | 1          |
| 32       | 4           | 1          |
+----------+-------------+------------+
输出: 
+----------+-------------+------------+
| order_id | customer_id | order_type |
+----------+-------------+------------+
| 31       | 4           | 1          |
| 32       | 4           | 1          |
| 1        | 1           | 0          |
| 2        | 1           | 0          |
| 11       | 2           | 0          |
| 22       | 3           | 0          |
+----------+-------------+------------+
解释: 
客户1有两个类型为0的订单。我们两个都返回。
客户2的订单类型为0,订单类型为1。我们只返回类型为0的订单。
客户3的订单类型为0,订单类型为1。我们只返回类型为0的订单。
客户4有两个类型1的订单。我们两个都返回。
# Write your MySQL query statement below
with  t1 as (select
customer_id #至少有一个类型为0的订单的客户
from
Orders
group by
customer_id
having
sum(if(order_type=0,1,0)) > 0
),
t2 as (
select
o.order_id,o.customer_id,o.order_type,t1.customer_id customer_id2
from
Orders o left join t1
using(customer_id)
)
select
order_id,customer_id,order_type
from
t2
where customer_id2 is null 
union  all
select
order_id,customer_id,order_type
from
t2
where customer_id2 is not null and order_type = 0
# Write your MySQL query statement below
with  t1 as (select
customer_id #至少有一个类型为0的订单的客户
from
Orders
group by
customer_id
having
sum(if(order_type=0,1,0)) > 0
),
t2 as (
select
o.order_id,o.customer_id,o.order_type,t1.customer_id customer_id2
from
Orders o left join t1
using(customer_id)
)
select
order_id,customer_id,order_type #没有类型为0的订单的用户的所有内容
from
t2
where customer_id2 is null 
union  all
select
order_id,customer_id,order_type #至少有一个类型为0的订单,不要报告该客户的任何类型为1的订单 的所有内容
from
t2
where customer_id2 is not null and order_type = 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值