leetcode : 175. combine two table
다이어그램
erDiagram
Person ||--o{ Address : has
Person {
int personId PK
string firstName
string lastName
}
Address {
int addressId PK
int personId FK
string city
string state
}
목표
Write a solution to
report the first name, last name, city, and state of each person
in the Person table.If the address of a personId is not present in the Address table, report null instead.
Return the result table in
any order
.
두 테이블을 조인해서 personId의 주소지 정보를 가져오기. (없으면 NULL)
문제 풀이
MySQL
SELECT
p.firstName,
p.lastName,
a.city,
a.state
FROM
person p
LEFT JOIN
address a ON p.personid = a.personid
- PERSON 테이블에 사람 정보가 있으면 Address 테이블에는 사람 정보가 없어도 가져와야한다.
- LEFT JOIN으로 가져오기.
Pandas
import pandas as pd
def combine_two_tables(person: pd.DataFrame, address: pd.DataFrame) -> pd.DataFrame:
joined = pd.merge(person, address,
on='personId', how='left')
cols = ['firstName','lastName','city','state']
return joined[cols]
- PERSON 테이블에 사람 정보가 있으면 Address 테이블에는 사람 정보가 없어도 가져와야한다.
- 재사용을 위해서 가져오기 cols를 따로 정의해주기.
코멘트
- 기본 JOIN 문제
'Data Analysis > Query' 카테고리의 다른 글
leetcode : 177. Nth Highest Salary (0) | 2024.12.28 |
---|---|
leetcode : 176. Second Highest Salary (0) | 2024.12.28 |
leetcode : 181. Employees Earning More Than Their Managers (0) | 2024.12.27 |
리트코드 : 3220. Odd and Even Transactions (0) | 2024.09.16 |
리트코드 : 2356. Number of Unique Subjects Taught by Each Teacher (0) | 2024.09.16 |
리트코드 : 1934. Confirmation Rate (0) | 2024.09.15 |
리트코드 : 1907. Count Salary Categories (0) | 2024.09.15 |
댓글