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
)
id | employee | snack | amount |
---|---|---|---|
1 | Alice | Chips | 5 |
2 | Bob | Candy | 3 |
3 | Alice | Soda | 4 |
4 | Bob | Chips | 6 |
5 | Alice | Candy | 2 |
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
employee | total_sales |
---|---|
Alice | 11 |
Bob | 9 |
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
Alice: 5 (Chips) + 4 (Soda) + 2 (Candy) = 11
Bob: 3 (Candy) + 6 (Chips) = 9
Other Useful Aggregates
Function | Description |
---|---|
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;