Exercise 1: Translating groupby("product")["revenue"].mean() Into SQL — Possible Solution ==================================================================== THE PANDAS CALL, PIECE BY PIECE ------------------------------ df.groupby("product")["revenue"].mean() breaks into three parts: "df.groupby('product')" groups all rows by their product value; "['revenue']" selects only the revenue column from within each group; ".mean()" computes the average of that column within each group. THE SQL EQUIVALENT ------------------------------ Following this chapter's own comment format for the .sum() example: SELECT product, AVG(revenue) FROM sales GROUP BY product; THE PIECE-BY-PIECE MAPPING ------------------------------ Per this chapter's own SQL-equivalent pattern for groupby/sum: - "df.groupby('product')" corresponds to SQL's "GROUP BY product" — both specify which column defines the groups rows get bucketed into. - "['revenue']" corresponds to naming "revenue" as the column being aggregated in the SELECT list, rather than some other column. - ".mean()" corresponds to SQL's AVG() aggregate function — the pandas method name and the SQL function name differ ("mean" vs. "AVG"), but both compute the arithmetic average of the selected column within each group. - The "product" column itself appears in the SQL SELECT list because SQL's GROUP BY requires selecting the grouping column explicitly to see which group each result row corresponds to; pandas' own groupby result implicitly carries the same information as its own resulting index, without needing to be separately selected. WHY THIS MAPPING HOLDS, PER THIS CHAPTER'S OWN EARLIER EXAMPLES ------------------------------ This chapter already demonstrated the identical structural pattern twice — df.groupby("product")["revenue"].sum() mapped directly onto "SELECT product, SUM(revenue) FROM sales GROUP BY product," and the .agg() example mapped onto a SELECT list with multiple aggregate functions. Swapping .sum() for .mean() changes only which aggregate function is applied, not the overall groupby-to-GROUP-BY structure — exactly why AVG() is the only piece of the SQL translation that differs from the chapter's own worked .sum() example. WHY THIS WORKS AS AN ANSWER ------------------------------ It maps every piece of the pandas call onto its SQL counterpart individually, using the exact translation pattern this chapter's own .sum() and .agg() examples already established, and explains why only the aggregate function itself (mean/AVG vs. sum/SUM) changes between the two examples.