1378. Replace Employee ID With The Unique Identifier
Problem Statement
Table: Employee
Column Name | Type |
---|---|
id | int |
name | varchar |
id
is theprimary key
(column with unique values) for this table.Each row of this table indicates the
name
of an employee and theirid
.
Table: EmployeeUNI
Column Name | Type |
---|---|
id | int |
unique_id | int |
(
id
,unique_id
) is the primary key (combination of columns with unique values) for this table.Each row of this table contains the id and the corresponding unique id of an employee in the company.
Instructions
- Write a solution to show the unique ID of each user, If a user does not have a unique ID replace just show
null
. - Return the result table in any order.
- The result format is in the following example.
Example
Input:
Employee
table
id | name |
---|---|
1 | Alice |
7 | Bob |
11 | Meir |
90 | Winston |
3 | Jonathan |
EmployeeUNI
table
id | unique_id |
---|---|
3 | 1 |
11 | 2 |
90 | 3 |
Output:
unique_id | name |
---|---|
null | Alice |
null | Bob |
2 | Meir |
3 | Winston |
1 | Jonathan |
Explanation:
Alice and Bob do not have a unique ID, We will show null instead.
The unique ID of Meir is 2.
The unique ID of Winston is 3.
The unique ID of Jonathan is 1.
Submissions
SELECT emuni.unique_id, em.name
FROM Employees em
LEFT JOIN EmployeeUNI emuni ON em.id = emuni.id
import pandas as pd
def replace_employee_id(employees: pd.DataFrame, employee_uni: pd.DataFrame) -> pd.DataFrame:
merged_df = pd.merge(employees, employee_uni, on='id', how='left')
result_df = merged_df[['unique_id', 'name']]
return result_df
Explanations
SELECT emuni.unique_id, em.name
: Select theunique_id
andname
columns from theEmployee
with and aliasem
andEmployeeUNI
with an aliasemuni
.FROM Employees em
: Select theEmployees
table and alias it asem
.LEFT JOIN EmployeeUNI emuni ON em.id = emuni.id
: This instruction performs a left outer join between theEmployees
table and theEmployeeUNI
table. The join condition is that theid
column inEmployees
matches theid
column inEmployeeUNI
. A left join ensures that all records from the left table (Employees
) are included in the result set, even if there is no matching record in the right table (EmployeeUNI
). For employees without a corresponding unique_id, theunique_id
field in the result set will beNULL
.
In summary, this query is designed to list all employees by name along with their unique identifiers if they have one. Employees without a unique identifier in the EmployeeUNI
table will still be listed, but their unique_id
will be shown as NULL
.