Join'lerle daha fazla pratik
Son egzersizde oluşturduğun seçme ifadesini yine kullanabilirsin; ancak bu kez küçük bir değişiklik yapıp yalnızca birkaç sütunu döndürelim ve diğer tabloyu bir group_by() ifadesinde kullanalım.
Bu egzersiz, kursun bir parçasıdır
Python ile Veritabanlarına Giriş
Egzersiz talimatları
- Şu alanları seçen bir ifade oluştur:
censustablosundanstatesütunu.censustablosundanpop2008sütununun toplamı.state_facttablosundancensus_division_namesütunu.
stmtifadesine.select_from()ekleyerekcensusvestate_facttablolarınıstatevenamesütunları üzerinden birleştir.- İfadeyi
state_facttablosununnamesütununa göre grupla. - Tüm kayıtları almak için
stmt_groupedifadesini çalıştır ve sonucuresultsolarak kaydet. resultsnesnesi üzerinde döngü kurup her kaydı yazdırarak yanıtı gönder.
Uygulamalı etkileşimli egzersiz
Bu egzersizi bu örnek kodu tamamlayarak deneyin.
# 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)