เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ฝึกเพิ่มเติมกับการ JOIN

ใช้คำสั่ง select เดิมจากแบบฝึกหัดที่แล้วได้เลย แต่คราวนี้เพิ่มความท้าทายด้วยการดึงเฉพาะบางคอลัมน์ และนำตารางอีกตารางไปใช้ใน คำสั่ง group_by()

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Python เบื้องต้นสำหรับฐานข้อมูล

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้างคำสั่งเพื่อ select:
    • คอลัมน์ state จากตาราง census
    • ผลรวมของคอลัมน์ pop2008 จากตาราง census
    • คอลัมน์ census_division_name จากตาราง state_fact
  • ต่อท้าย .select_from() เข้ากับ stmt เพื่อ JOIN ตาราง census และ state_fact โดยใช้คอลัมน์ state และ name
  • จัดกลุ่มคำสั่งด้วยคอลัมน์ name ของตาราง state_fact
  • รันคำสั่ง stmt_grouped เพื่อดึงข้อมูลทั้งหมดและบันทึกไว้ในตัวแปร results
  • กด ส่งคำตอบ เพื่อวนลูปผ่านออบเจ็กต์ results และพิมพ์แต่ละรายการ

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# 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)
แก้ไขและรันโค้ด