Skip to content

Files

Latest commit

c29b144 · May 17, 2024

History

History

2084.Drop Type 1 Orders for Customers With Type 0 Orders

comments difficulty edit_url tags
true
中等
数据库

English Version

题目描述

活动表: 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的订单。我们两个都返回。

解法

方法一

MySQL

# Write your MySQL query statement below
WITH
    T AS (
        SELECT DISTINCT customer_id
        FROM Orders
        WHERE order_type = 0
    )
SELECT *
FROM Orders AS o
WHERE order_type = 0 OR NOT EXISTS (SELECT 1 FROM T AS t WHERE t.customer_id = o.customer_id);

方法二

MySQL

SELECT DISTINCT
    a.order_id,
    a.customer_id,
    a.order_type
FROM
    Orders AS a
    LEFT JOIN Orders AS b ON a.customer_id = b.customer_id AND a.order_type != b.order_type
WHERE b.order_type IS NULL OR b.order_type = 1;