Group by in SQL
Written By:- Isha MalhotraGroup By
Group by is used to display data in groups based on aggregate function. Sometimes you need to show data in some groups with some aggregate function, In this situation we can use group by statement.
Example of Group By
Check the data of following table. Suppose you want to show the sum of all no of prod according to year. In that case you use group by statement.
Figure 1
You will use the query as follows:-
select prod_year, SUM(no_of_prod) as 'Final Production' from prod_rep group by Prod_year;
Figure 2
We can also implement grouping of more than one column.
select prod_year,dept, SUM(no_of_prod) as 'Final Production' from prod_rep group by Prod_year,dept;
Now it will group data first according to prod year and after that according to dept.the output of this query is as follows:-
Figure 3