SQL Group by Clause

SQL Group by Clause

Hi friends, in this post we will learn about SQL Group by Clause. Group By clause is used to group the result.

Earlier we had discussed about SQL Order By Clause,SQL Select Top ClauseLike Clause SQL ServerSQL AND & OR OperatorsSQL Where Clause, Delete Query SQL Server, SQL Update Statement, SQL Select Statement, SQL Insert Statement, Drop Table SQL Server, Rename Table in SQL Server, Create Table SQL Server, Schema In SQL Server, SQL Server Operators, Data Type in SQL Server and Drop-Delete SQL Server Database Using Management Studio or Query.

Table Structure 1: 

ID NAME AGE ADDRESS SALARY
1 MANN 30 GURGAON 20000
2 JAI 21 Delhi 15000
3 AMAN 33 Kota 12000
4 AMIT 25 Mumbai 6000
5 SURESH 37 Bhopal 8000
6 Komal 22 GURGAON 4000

in above table we have all names are unique, so group by does not work.

SQL Group by Query Example 1: 

----SELECT DATABASE----
USE HIGHTECHNOLOGY
GO
----GROUP BY EXAMPLES----
----GROUP BY WITH DISTINCT NAME----
SELECT NAME, SUM(SALARY) FROM EMPLOYEE GROUP BY NAME 
GO

SQL Group by Clause


Table Structure 2:

ID NAME AGE ADDRESS SALARY
1 MANN 30 GURGAON 20000
2 JAI 21 Delhi 15000
3 AMAN 33 Kota 12000
4 AMIT 25 Mumbai 6000
5 SURESH 37 Bhopal 8000
6 Komal 22 GURGAON 4000
7 MANN 31 DELHI 22000

In above table we have one duplicate name ‘MANN‘, so group by works and group the result set by name. Hence it groups result of name MANN.

SQL Group by Query Example 2: 

----SELECT DATABASE----
USE HIGHTECHNOLOGY
GO
----GROUP BY EXAMPLES----
----GROUP BY WITH ONE NAME DUPLICATE----
SELECT NAME, SUM(SALARY) FROM EMPLOYEE GROUP BY NAME 
GO

GROUP BY SQL