Luyện tập thêm với join
Bạn có thể dùng lại câu lệnh select đã xây dựng ở bài trước, tuy nhiên,
hãy thay đổi một chút: chỉ trả về một vài cột và dùng bảng còn lại trong mệnh đề
group_by().
Bài tập này là một phần của khóa học
Nhập môn Cơ sở dữ liệu với Python
Hướng dẫn bài tập
- Xây dựng một câu lệnh để chọn:
- Cột
statetừ bảngcensus. - Tổng của cột
pop2008từ bảngcensus. - Cột
census_division_nametừ bảngstate_fact.
- Cột
- Gắn
.select_from()vàostmtđể join hai bảngcensusvàstate_facttheo các cộtstatevàname. - Nhóm câu lệnh theo cột
namecủa bảngstate_fact. - Thực thi câu lệnh
stmt_groupedđể lấy tất cả bản ghi và lưu vàoresults. - Gửi câu trả lời để lặp qua đối tượng
resultsvà in từng bản ghi.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# Build a statement to select the state, sum of 2008 population and census
# division name: stmt
stmt = select([
____,
func.sum(____),
____
])
# Append select_from to join the census and state_fact tables by the census state and state_fact name columns
stmt_joined = stmt.select_from(
census.join(____, census.columns.____ == state_fact.columns.____)
)
# Append a group by for the state_fact name column
stmt_grouped = stmt_joined.group_by(____)
# Execute the statement and get the results: results
results = connection.execute(____).fetchall()
# Loop over the results object and print each record.
for record in results:
print(record)