*Basic Group By
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department;
*Group By With SUM()
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id;
*Group By Multiple Columns
SELECT department, job_title, COUNT(*) AS total
FROM employees
GROUP BY department, job_title;
*Group By With Having
SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
Why Use HAVING with GROUP BY in SQL?
-
The
GROUP BYclause groups rows based on one or more columns. -
The
HAVINGclause filters groups after aggregation (likeWHEREbut for groups instead of individual rows).
