The GROUP BY
clause is used to group rows with the same values in specified columns into summary rows, often used with Aggregate functions (e.g., COUNT
, SUM
, AVG
, MAX
, MIN
) to perform calculations on groups of data.
منقدرش نستخدمها مع الـ WHERE انما نقدر نستخدمها مع HAVING بس
Syntax:
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
Key Points:
- Purpose: Groups rows based on column values.
- Aggregate Functions: Works with aggregate functions to provide meaningful summaries for each group.
- Mandatory for Aggregates on Grouped Data: If a column is not in an aggregate function, it must be in the
GROUP BY
clause.
Examples:
1. Basic Grouping
Group employees by their department and calculate the total salary for each department:
SELECT department, SUM(salary) AS total_salary
FROM Employees
GROUP BY department;
Output:
department | total_salary |
---|---|
Sales | 150000 |
HR | 80000 |
IT | 120000 |
2. Grouping with Multiple Columns
Group employees by department and job title, and calculate the average salary:
SELECT department, job_title, AVG(salary) AS avg_salary
FROM Employees
GROUP BY department, job_title;
Output:
department | job_title | avg_salary |
---|---|---|
Sales | Sales Manager | 75000 |
HR | HR Specialist | 40000 |
IT | Software Engineer | 60000 |
3. Filtering Groups Using HAVING
The HAVING
clause filters groups after grouping, similar to how WHERE
filters rows before grouping.
Find departments with total salaries greater than 100,000:
SELECT department, SUM(salary) AS total_salary
FROM Employees
GROUP BY department
HAVING SUM(salary) > 100000;
Output:
department | total_salary |
---|---|
Sales | 150000 |
IT | 120000 |
4. Using GROUP BY with COUNT
Count the number of employees in each department:
SELECT department, COUNT(employee_id) AS num_employees
FROM Employees
GROUP BY department;
Output:
department | num_employees |
---|---|
Sales | 3 |
HR | 2 |
IT | 2 |
Group by + Order by
لو عايز تستخدم GROUP BY
مع ORDER BY
في استعلام SQL Server، بتجمع القيم على حسب عمود معين باستخدام GROUP BY
، وبعد كده ترتب النتائج باستخدام ORDER BY
.
الصيغة العامة:
SELECT column1, aggregate_function(column2) AS alias
FROM table_name
GROUP BY column1
ORDER BY column1 [ASC|DESC];
شرح:
- الـ
column1
: العمود اللي هتعمل عليه التجميع. - الـ
aggregate_function(column2)
: دالة تجميعية زيSUM
,COUNT
,AVG
,MAX
, أوMIN
اللي بتشتغل على عمود معين. - الـ
GROUP BY column1
: بتحدد العمود اللي هتعمل عليه التجميع. - الـ
ORDER BY column1 [ASC|DESC]
: ترتيب النتائج تصاعديًا (ASC) أو تنازليًا (DESC).
مثال عملي:
الهدف:
لو عندك جدول Sales
وفيه الأعمدة ProductID
وQuantity
، وعايز:
- تجمع الكميات (
Quantity
) لكل منتج. - ترتب المنتجات حسب الكمية تنازليًا.
الكود:
SELECT ProductID, SUM(Quantity) AS TotalQuantity
FROM Sales
GROUP BY ProductID
ORDER BY TotalQuantity DESC;
النتيجة:
- كل صف هيمثل منتج واحد (
ProductID
) مع إجمالي الكمية المباعة (TotalQuantity
). - المنتجات مرتبة تنازليًا حسب إجمالي الكمية.
Common Use Cases:
- Summarizing Data: Calculating totals, averages, or other summaries for specific groups (e.g., revenue by region).
- Counting Records: Determining the count of items within each group (e.g., number of orders per customer).
- Filtering Summarized Data: Using
HAVING
to filter groups based on aggregate values (e.g., only show departments with more than 5 employees).
Difference Between WHERE and HAVING:
Aspect | WHERE | HAVING |
---|---|---|
Purpose | Filters rows before grouping. | Filters groups after grouping. |
Works On | Individual rows. | Aggregated data (e.g., SUM , COUNT ). |
Example | WHERE salary > 50000 | HAVING SUM(salary) > 100000 |
Summary:
GROUP BY
: Organizes data into groups for analysis.- Aggregate Functions: Used to calculate metrics like
SUM
,COUNT
, orAVG
within groups. HAVING
Clause: Filters groups based on aggregated values.- A vital tool for summarizing and analyzing structured data in SQL.