返回介绍

solution / 2000-2099 / 2084.Drop Type 1 Orders for Customers With Type 0 Orders / README_EN

发布于 2024-06-17 01:03:11 字数 3271 浏览 0 评论 0 收藏 0

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

中文文档

Description

Table: Orders

+-------------+------+
| Column Name | Type |
+-------------+------+
| order_id  | int  | 
| customer_id | int  |
| order_type  | int  | 
+-------------+------+
order_id is the column with unique values for this table.
Each row of this table indicates the ID of an order, the ID of the customer who ordered it, and the order type.
The orders could be of type 0 or type 1.

 

Write a solution to report all the orders based on the following criteria:

  • If a customer has at least one order of type 0, do not report any order of type 1 from that customer.
  • Otherwise, report all the orders of the customer.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input:
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      |
+----------+-------------+------------+
Output:
+----------+-------------+------------+
| order_id | customer_id | order_type |
+----------+-------------+------------+
| 31     | 4       | 1      |
| 32     | 4       | 1      |
| 1    | 1       | 0      |
| 2    | 1       | 0      |
| 11     | 2       | 0      |
| 22     | 3       | 0      |
+----------+-------------+------------+
Explanation:
Customer 1 has two orders of type 0. We return both of them.
Customer 2 has one order of type 0 and one order of type 1. We only return the order of type 0.
Customer 3 has one order of type 0 and one order of type 1. We only return the order of type 0.
Customer 4 has two orders of type 1. We return both of them.

Solutions

Solution 1

# 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);

Solution 2

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;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文