Ravindra BagaleCourses & study guides Track your progress

12. GROUP BY: One Row Per Group

12.3 How to Group by Two Columns (City and Product)

Why. Two keys answer “city and product” style pivots.

What. GROUP BY city, product_id (or names via join later).

How. List every non-aggregated column in GROUP BY.

Steps

  1. Group by city and product_id.
  2. Order by city then sales.
  3. Read one city block.

Examples

Example 1 · dataset: raja_coffee

SELECT city, product_id,
       COUNT(*) AS orders,
       ROUND(SUM(amount_inr),2) AS sales_inr
FROM orders
GROUP BY city, product_id
ORDER BY city, sales_inr DESC;

Output

cityproduct_idorderssales_inr
Goa1021890.0
Goa1031360.0
Goa1041350.0
Kolhapur1031900.0
Kolhapur1021890.0
Kolhapur1051620.0
Mumbai1051930.0
Mumbai1011840.0
Mumbai1031720.0
Nashik10311080.0
Nashik1021890.0
Nashik1041350.0
Pune10222670.0
Pune10122520.0
Pune10432100.0
Pune10321260.0
Pune1051620.0
Solapur1011420.0
Solapur1051310.0

Meaning. One row per city+product pair.

Ravindra Bagale's Tip

More GROUP BY columns ⇒ more (finer) rows in the result.