TechnoLearnAcademy

TECHNOLEARN

SQL GROUP BY WITH WHERE

THE SQL GROUP BY Statement is used to group rows that have the same values in specified columns into summary rows.
We can apply aggregate functions like SUM, COUNT, AVG, MAX, or MIN to calculate values for each group.

Syntax:      

                SELECT  column1 , aggregate_function(column2)                                                                                                                                                                                           FROM tablename                                                                                                                                                                                WHERE condition                                                                                                                                                                                  GROUP BY column1                                                                                                                                                                               ORDER BY column1; 
Let’s understand the group by statement with an example. For demonstration purposes, we will be using the table emp.
         Table Emp

Example:

   Objective: In this example, we will count the number of employees in each department.
                     SELECT Department , COUNT(Ecode) as [TotalCount] FROM Tbl_Emp
                                                        GROUP BY Department
                                                        ORDER BY Department;
    Output:
Note: In this example, Order by clause is used to sort the Departments in ascending order.

Example:

   Objective: In this example, we will find the sum of salary for each department.
                     SELECT Department , SUM(Salary) as [TotalSalary] FROM Tbl_Emp
                                                        GROUP BY Department
                                                        ORDER BY Department;
    Output:
Note: We can use Max, Min and Avg functions to find the Max, Min and Avg Salary of each department.

Example:

   Objective: In this example, we will find the sum of salary for the IT department only.
                     SELECT Department , SUM(Salary) as [TotalSalary] FROM Tbl_Emp
                                                        WHERE Department = ‘IT’
                                                        GROUP BY Department;
    Output:
Scroll to Top