王廷瑋|數位醫療|智慧醫療: 183. Customers Who Never Order WFU

2024年7月11日 星期四

183. Customers Who Never Order

183. Customers Who Never Order


顧客表

+-------------+---------+

| 列名 | 類型 |

+-------------+---------+

| id | int | | name | varchar |

+-------------+---------+

id 是這個表的主鍵(具有唯一值的列)。 這個表的每一行表示一個顧客的 ID 和姓名。
訂單表

+-------------+------+

| 列名 | 類型 |

+-------------+------+

| id | int |

| customerId | int |

+-------------+------+

id 是這個表的主鍵(具有唯一值的列)。 customerId 是一個外鍵(引用列),引用自顧客表的 ID。 這個表的每一行表示一個訂單的 ID 和下訂單的顧客的 ID。
解題說明

撰寫一個解決方案來查找所有從未下過訂單的顧客。

可以按任意順序返回結果表。

範例:

輸入:

顧客表:

+----+-------+

| id | name |

+----+-------+

| 1 | Joe |

| 2 | Henry |

| 3 | Sam |

| 4 | Max |

+----+-------+

訂單表:

+----+------------+

| id | customerId |

+----+------------+

| 1 | 3 |

| 2 | 1 |

+----+------------+

輸出:

+-----------+

| Customers |

+-----------+

| Henry |

| Max |

+-----------+


MySQL


# Write your MySQL query statement below

SELECT name AS Customers
FROM Customers
LEFT JOIN Orders ON Customers.id = Orders.customerId
WHERE Orders.customerId IS NULL;

510ms


Pandas


import pandas as pd

def find_customers(customers: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
# Perform a left join on customers and orders
merged_df = customers.merge(orders, left_on='id', right_on='customerId', how='left')
# Filter rows where customerId in orders is NaN
no_orders_df = merged_df[merged_df['customerId'].isna()]
# Select the name column and rename it to Customers
result_df = no_orders_df[['name']].rename(columns={'name': 'Customers'})
return result_df

66.51MB, 492ms


PostgreSQL


-- Write your PostgreSQL query statement below

SELECT c.name AS Customers
FROM Customers c
LEFT JOIN Orders o ON c.id = o.customerId
WHERE o.customerId IS NULL;

0.00MB, 242ms