Joins का और अभ्यास
आप पिछली एक्सरसाइज में बनाया हुआ वही select स्टेटमेंट इस्तेमाल कर सकते हैं. लेकिन इस बार थोड़ी ट्विस्ट जोड़ते हैं: केवल कुछ कॉलम वापस लें और group_by() क्लॉज़ में दूसरी टेबल का उपयोग करें.
यह अभ्यास पाठ्यक्रम का हिस्सा है
Python में Databases का परिचय
अभ्यास निर्देश
- ऐसा स्टेटमेंट बनाइए जो चुने:
censusटेबल सेstateकॉलम.censusटेबल सेpop2008कॉलम का sum.state_factटेबल सेcensus_division_nameकॉलम.
stmtमें.select_from()जोड़ें ताकिcensusऔरstate_factटेबल्स कोstateऔरnameकॉलम्स पर join किया जा सके.- स्टेटमेंट को
state_factटेबल केnameकॉलम द्वारा group कीजिए. - सभी रिकॉर्ड पाने के लिए स्टेटमेंट
stmt_groupedको execute करें और उसे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)