Skip to main content

LeetCode 2084. Drop Type 1 Orders for Customers with Type 0 Orders SQL Solution

Problem

LeetCode SQL Problem

  1. Drop Type 1 Orders for Customers with Type 0 Orders

Orders table

order_idcustomer_idorder_type
110
210
1120
1221
2131
2230
3141
3241

Solution - Self Join, CTE, Subquery

Drop Type 1 Orders for Customers with Type 0 Orders
-- Find customers that have at least one order of type 0.
-- Do not return any order of type 1 from these customers
WITH CustomerIds_OnlyReturnTypeZero
AS (
SELECT DISTINCT (L.customer_id) AS customer_id
FROM Orders AS L
INNER JOIN Orders AS R ON L.order_id < R.order_id
AND L.customer_id = R.customer_id
WHERE L.order_type - R.order_type <> 0
)
SELECT *
FROM Orders AS O
WHERE O.order_type = 0 -- Always return type 0 order
OR (
-- Only return type 1 order if the customer does not have any type 0 order
O.order_type = 1
AND O.customer_id NOT IN (
SELECT customer_id
FROM CustomerIds_OnlyReturnTypeZero
)
)

Query Output

order_idcustomer_idorder_type
110
210
1120
2230
3141
3241

Solution - Group By, CTE, Subquery

Drop Type 1 Orders for Customers with Type 0 Orders
-- Find customers that have at least one order of type 0.
-- Do not return any order of type 1 from these customers
WITH CustomerIds_OnlyReturnTypeZero
AS (
SELECT DISTINCT (L.customer_id) AS customer_id
FROM Orders AS L
INNER JOIN Orders AS R ON L.order_id < R.order_id
AND L.customer_id = R.customer_id
WHERE L.order_type - R.order_type <> 0
)
SELECT *
FROM Orders AS O
WHERE O.order_type = 0 -- Always return type 0 order
OR (
-- Only return type 1 order if the customer does not have any type 0 order
O.order_type = 1
AND O.customer_id NOT IN (
SELECT customer_id
FROM CustomerIds_OnlyReturnTypeZero
)
)

Query Output

order_idcustomer_idorder_type
110
210
1120
2230
3141
3241

Solution - Correlated Subquery

Drop Type 1 Orders for Customers with Type 0 Orders
SELECT *
FROM Orders AS O
WHERE O.order_type = 0 -- Always return type 0 order
OR (
-- Only return type 1 order if the customer does not have any type 0 order
O.order_type = 1
AND NOT EXISTS (
SELECT *
FROM Orders S
WHERE S.customer_id = O.customer_id
AND S.order_type = 0
)
)

Query Output

order_idcustomer_idorder_type
110
210
1120
2230
3141
3241