Ravindra BagaleCourses & study guides Track your progress

12. GROUP BY: One Row Per Group

12.1 Why GROUP BY Is the SQL PivotTable

Why. Excel users know PivotTables — GROUP BY is that idea in SQL.

What. GROUP BY builds one output row per group of values.

How. SELECT city, SUM(amount_inr) FROM orders GROUP BY city;

Steps

  1. Say the group key (city).
  2. Pick the aggregate (SUM).
  3. Remember: non-aggregated columns must be in GROUP BY.

Examples

Example 1 · dataset: raja_coffee

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

Output

citysales_inr
Pune9170.0
Mumbai2490.0
Kolhapur2410.0
Nashik2320.0
Goa1600.0
Solapur730.0

Meaning. Pivot-like: city on rows, sum of sales.

Ravindra Bagale's Tip

See also /guides/excel-vs-sql.html for the Excel term map.