Pivot Tables: GROUP BY + aggregate functions

Imagine This…

You run a small snack shop. At the end of each day, you record which employee sold what snack and for how much.

Your Sales Table (snack_sales)

idemployeesnackamount
1AliceChips5
2BobCandy3
3AliceSoda4
4BobChips6
5AliceCandy2

Goal

You want to know: How much did each employee sell in total?

SQL Query

SELECT employee, SUM(amount) AS total_sales
FROM snack_sales
GROUP BY employee;
  

Expected Output

employeetotal_sales
Alice11
Bob9

How It Works

  • GROUP BY employee – SQL gathers all the rows for each employee.
  • SUM(amount) – Adds up the sales amount for each group.
  • AS total_sales – Assigns a label to the result column.
Breakdown:
Alice: 5 (Chips) + 4 (Soda) + 2 (Candy) = 11
Bob: 3 (Candy) + 6 (Chips) = 9

Other Useful Aggregates

FunctionDescription
SUM()Adds values
AVG()Calculates the average
COUNT()Counts rows
MAX()Finds the highest
MIN()Finds the lowest

Example: Average Sales per Employee

SELECT employee, AVG(amount) AS avg_sale
FROM snack_sales
GROUP BY employee;
  

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top