Aggregation functions are used to summarize data, especially when working with grouped values.
1๏ธโฃ Common Aggregate Functions
โฆ COUNT() โ Total number of rows
โฆ SUM() โ Adds up numeric values
โฆ AVG() โ Calculates the average
โฆ MIN() / MAX() โ Finds smallest/largest value
Example:
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
โก๏ธ Returns the number of employees in each department.
2๏ธโฃ GROUP BY
Used with aggregate functions to group rows based on column values.
SELECT city, AVG(salary)
FROM employees
GROUP BY city;
โก๏ธ Shows average salary by city.
3๏ธโฃ HAVING vs WHERE
โฆ WHERE filters rows before grouping
โฆ HAVING filters groups after aggregation
Example:
SELECT dept_id, COUNT(*)
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5;
โก๏ธ Shows departments with more than 5 employees.
4๏ธโฃ GROUP BY Multiple Columns
SELECT dept_id, role, COUNT(*)
FROM employees
GROUP BY dept_id, role;
โก๏ธ Groups by department and role for detailed summaries.
5๏ธโฃ Real-World Use Cases
โ Sales by region
โ Orders per customer
โ Avg. rating per product
โ Monthly revenue reports
๐ฌ Tap โค๏ธ for more!