GROUP BY in SQL Server


As the name suggests, GROUP BY command is used to GROUP the data based on certain criteria or based on the required columns.


GROUP BY is considered as one of the complex commands in SQL Server because of its syntax.

A general GROUP BY clause includes GROUPING SETS, CUBE, ROLLUP, WITH CUBE, or WITH ROLLUP. All these complex clauses which are used along with GROUP BY will be discussed later.

As of now, we will concentrate more on only GROUP BY clause and will make the things simple.

As mentioned earlier GROUP BY is the clause used to group data based on the given criteria.

Syntax for the simple GROUP BY is:

SELECT <Column Names> FROM <table Name> GROUP BY <Column Names>

Note: All the columns which needs to be retrieved in the select command , they should present in the GROUP BY clause.

Example:

Let consider the scenario in which a table holds students names and there subject details.

To group the students based on the subjects that they have selected , we can use the below query:

Query:

SELECT ID,NAME, SUBJECT FROM STUDENTS GROUP BY SUBJECT, ID,NAME

Below picture shows the difference between normal SELECT query and the SELECT query along with GROUP BY Command.

Result Set:






This entry was posted in . Bookmark the permalink.

Leave a reply