SQL Group By is one of the most important concepts of SQL. It is used to group the data by similar values.
There are many ways by which you can use Group By but the most confusing one is Group by with multiple columns.
For example, we are going to use the table below.
SELECT * FROM STUDENTS;
Now let us use GROUP BY clause to find the average of student marks-
SELECT STUDENTID, AVG(MARKS) FROM STUDENTS GROUP BY STUDENTID;
Keep in mind Group By clause is mostly used when we aggregate some values that is why there is aggregate in SELECT statement.
If we don’t use aggregate, an error will be thrown
Now let’s suppose, you want to Group By with multiple columns
SELECT STUDENTID,SUBJECT, AVG(MARKS) FROM STUDENTS GROUP BY STUDENTID, SUBJECT;
That’s how you use Group By with multiple columns
How many columns can we use in Group by clause?
The answer to the above question is ( Number of columns in SELECT list – 1)
Source:- Microsoft T-SQL Documentation