Skip to content

1378. Replace Employee ID With The Unique Identifier

Problem Statement

Table: Employee

Column NameType
idint
namevarchar

id is the primary key (column with unique values) for this table.

Each row of this table indicates the name of an employee and their id.

Table: EmployeeUNI

Column NameType
idint
unique_idint

(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

idname
1Alice
7Bob
11Meir
90Winston
3Jonathan

EmployeeUNI table

idunique_id
31
112
903

Output:

unique_idname
nullAlice
nullBob
2Meir
3Winston
1Jonathan

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

sql
SELECT emuni.unique_id, em.name
FROM Employees em
LEFT JOIN EmployeeUNI emuni ON em.id = emuni.id
python
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

PostgreSQL
Submitted by @noeyislearning
  • SELECT emuni.unique_id, em.name: Select the unique_id and name columns from the Employee with and alias em and EmployeeUNI with an alias emuni.
  • FROM Employees em: Select the Employees table and alias it as em.
  • LEFT JOIN EmployeeUNI emuni ON em.id = emuni.id: This instruction performs a left outer join between the Employees table and the EmployeeUNI table. The join condition is that the id column in Employees matches the id column in EmployeeUNI. 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, the unique_id field in the result set will be NULL.

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.

Pandas
Submitted by @noeyislearning