GROUP BY Clause
GROUP BY Clause is used to group the table based on the value of one or multiple columns and on that group to apply the aggregate functions to find some results.
Example 1: Number of Employees in Each Deparment Using GROUP BY Clause
If We Have to Find the Employees in Each Department Then We Can Use GROUP BY Clause.
Query:
SELECT Department, COUNT(*) AS Count
FROM employee
GROUP BY Department;
Output:
Explanation: Similarly, if we have to find the SUM of salary given to each department or the maximum salary given to the department then we can do this very easily using GROUP BY Clause.
Example 2: Total Salary and Maximum Salary with Department
Let’s calculate the total salary of employees and also find the maximum salary along with the department grouped by Department.
Query:
SELECT Department, SUM(Salary) AS Total_Salary
FROM employee
GROUP BY Department
GO;
SELECT Department, MAX(Salary) AS Maximum_Salary
FROM employee
GROUP BY Department
GO;
Output:
Explanation: GROUP BY clause is always used with aggregate functions and it is used to generate the result from those groups.
Group By Vs Distinct Difference In SQL Server
Distinct is a relational database management system. SQL Server offers a wide range of features and tools that handle different needs, from small-scale applications to large-scale application solutions. GROUP BY has performance features, especially when dealing with large datasets and complex aggregations. DISTINCT is generally more effective and more efficient when the purpose is to obtain unique values.
In this article, we will understand the Group By vs. Distinct Difference In SQL Server with examples and so on.