SQL Group By:
The SQL GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s) ORDER BY column_name(s);
To fetch the total amount of salary on each Employee, then GROUP BY query would be as follows:
SELECT EmpName, SUM(SALARY) AS SALARY FROM SAMPLETABLE GROUP BY EmpName;
Here I have executed both the queries to show you the output of SAMPLETABLE and the output of SAMPLETABLE with GROUP BY statement.
Now, I have modified the data in the SAMPLETABLE. I have added some duplicate records.
Again I am executing both the queries to show you the output of SAMPLETABLE and the output of SAMPLETABLE with GROUP BY statement.
In the below image, we could see two queries. You could find duplicate values in the table name SAMPLETABLE. Total number of records are 4 based on GROUP BY in the second SELECT query. SELECT GROUP BY statement displays two columns (such as EmpName and SALARY) and grouped the records with the EmpName column.
In the next tutorial, we will see how to use HAVING in SQL
Check out the complete SQL Tutorial by clicking on below link: