题目
Easy
Table: Person
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| PersonId | int |
| FirstName | varchar |
| LastName | varchar |
+-------------+---------+
PersonId is the primary key column for this table.
Table: Address
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| AddressId | int |
| PersonId | int |
| City | varchar |
| State | varchar |
+-------------+---------+
AddressId is the primary key column for this table.
Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:
FirstName, LastName, City, State
解法
这道题需要注意的是不论有没有address,都需要返回person name,所以需要left join。
SQL
select p.FirstName, p.LastName, a.City, a.State
from Person p
left join address a
on p.PersonId = a.PersonId
Pandas
下面先用pandas建立了两个table, 然后通过 pd.merge
将两个table join在一起,how='left'
来表示是left join。合并完两个table之后,选出需要返回的列。
import pandas as pd
person = pd.DataFrame([[1, "Wang", "Allen"]], columns=["PersonId", "LastName", "FirstName"])
address = pd.DataFrame([[1, 2, "New York City", "New York"]], columns=["AddressId", "PersonId", "City", "State"])
pd.merge(person, address, on='PersonId', how='left')[['LastName', 'FirstName', 'City', 'State']]