SQL Group By

The SQL Group By statement is used to group identical values ​​into summary rows such as "Search the number of users in each state". The GROUP BY statement is often used with aggregate functions and follows the WHERE clause in a select statement.

Group By Syntax :

The syntax of the Group By is −

SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2



Group By Example :

Consider the Customer table with the following records -

CustomerID CustomerName Age Address CustomerSalary
1 Aarav 28 Udaipur 28000
2 Vivaan 25 Mumbai 30000
3 Reyansh 28 Chennai 35000
4 Muhammad 25 Udaipur 50000
5 Sai 30 Mumbai 27000


TEST CASE 1 :- The following code is an example, which would select the Address and sum of CustomerSalary from the Customer table GROUP BY Address.

SELECT Address, SUM(CustomerSalary) FROM Customer
GROUP BY Address;


The result for the respective sql query is as follows −

Address CustomerSalary
Chennai 35000
Mumbai 57000
Udaipur 78000



TEST CASE 2:- The following code is an example, which would select the Age and sum of CustomerSalary from the Customer table GROUP BY Age.

SELECT Age, SUM(CustomerSalary) FROM Customer
GROUP BY Age;


The result for the respective sql query is as follows −

Age CustomerSalary
25 80000
28 63000
30 27000



Visit :


Discussion



* You must be logged in to add comment.