SQL Server BasicsWhat is SQL Server database?What is RDBMS?What is Normalization?Why we use Denormalization?What_is_SQL?What is PL/SQL?Difference between SQL and PL/SQLDatabase TableOne to One RelationshipOne to Many RelationshipMany to Many RelationshipMany to One RelationshipString Data TypesNumber Data TypesDate Data TypesOther Data TypesCreate DatabaseDrop DatabaseCreating and Managing Users in SQL ServerCreate TableAlter TableDrop TableConstraints in SQL serverPrimary KeyForeign KeyUnique KeyCandidate KeyComposite KeyDifference between primary key and candidate keyPrimary key and foreign key relationshipSurrogate KeyCascading Referential Integrity ConstraintsSelf Referential Integrity ConstraintsInsert into statementInsert multiple recordsUpdate statementDelete statementTruncate statementDifference between Delete and TruncateAlias in SQL ServerSelect statementSelect DistinctSelect TopSelect IntoNull Functions(ISNULL(),NULLIF(),COALESCE())Sub QueryIdentity ColumnSequence objectDifference between sequence and identity columnSQL Server ClausesWHERE ClauseOrder By ClauseTop N ClauseGroup By ClauseHaving ClauseDifference between Where and HavingSQL Server OperatorsArithmetic OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsAny OperatorsAll OperatorsUnion OperatorsUnion All OperatorsDifference between Union and Union AllIntersect OperatorExcept OperatorDifference between Except and IntersectJoinsInner JoinLeft JoinRight JoinFull JoinSelf JoinCross JoinViewsWhat are views?Create views using SSMSIndexed ViewsComplex ViewsCheck Option in ViewCheck Encryption in ViewSchema Binding Option in ViewRead-only ViewsUpdatable ViewsAdvantages and disadvantages of viewsCreate multiple views on one tableCan we implement index on views?Can we Perform Insert, update, delete operation on views?Stored Procedure and FunctionsWhat are Stored Procedures?Why we use stored procedures?Passing parameters to Stored procedureUser-Defined FunctionsDifference between UDF and Stored procedurePre-Defined Functions@@Indentity and Scope_IndentityNULLIF, ISNULL and COALESCE

SQL - Group By Clause

The GROUP BY clause in SQL Server is used to group rows based on one or more columns in a query. It is often used in conjunction with aggregate functions like SUM, COUNT, AVG, and MAX to perform calculations on groups of rows. The GROUP BY clause divides the result set into groups based on the specified columns and applies aggregate functions to each group.

The basic syntax of the GROUP BY clause is as follows:


SELECT column1, column2, ..., aggregate_function(column)
FROM table_name
GROUP BY column1, column2, ...;

In the above syntax, column1, column2, ... represent the columns you want to group by, and aggregate_function(column) represents the aggregate function you want to apply to each group.

Let's explore how you can use the GROUP BY clause with an "Orders" table that contains fields such as "OrderID", "CustomerID", "ProductID", and "Quantity".
Assuming you have an "Orders" table with the following sample data:

Table: Orders
OrderID CustomerID ProductID Quantity
110115
210123
310212
410334
510221
610132
710313
810232

Now, let's say you want to use GROUP BY to find the total quantity of each product ordered by customers. You can write a query like this:


SELECT
    ProductID,
    SUM(Quantity) AS TotalQuantity
FROM
    Orders
GROUP BY
    ProductID;

In this query:

  • We select the "ProductID" column to identify each product.
  • We use the SUM function to calculate the total quantity of each product ordered.
  • We give an alias to the calculated column using AS TotalQuantity to make the result more readable.
  • We use the GROUP BY clause to group the rows by "ProductID," so each group represents a unique product.

The result of this query would be:

ProductID TotalQuantity
110
24
38
This result shows the total quantity of each product ordered by customers.

You can include multiple columns in the GROUP BY clause to create more granular groups. In such cases, the result set will be grouped based on the combination of values in the specified columns.

Here's a new set of sample data that includes multiple records for the same customer ordering the same product, allowing us to demonstrate the GROUP BY with both columns:

Table: Orders
OrderID CustomerID ProductID Quantity
110115
210113
310212
410334
510211
610112
710313
810232

Here's an example that groups the orders by both CustomerID and ProductID:


SELECT 
	CustomerID, 
	ProductID, 
	SUM(Quantity) AS TotalQuantity
FROM 
	Orders
GROUP BY 
	CustomerID, 
	ProductID;

In this query:

  • We select both "CustomerID" and "ProductID" columns to identify each customer's orders for each product.
  • We use the SUM function to calculate the total quantity of each product ordered by each customer.
  • We give an alias to the calculated column using AS TotalQuantity to make the result more readable.
  • We use the GROUP BY clause to group the rows by both "CustomerID" and "ProductID," creating unique groups for each combination of customer and product.

The result of this query would be:

CustomerID ProductID TotalQuantity
101110
10213
10232
10313
10334

This result displays the total quantity of each product ordered by each customer. Each row represents a unique combination of "CustomerID" and "ProductID."

When using the GROUP BY clause, it's important to note that any column included in the SELECT clause must either be part of the GROUP BY clause or an aggregate function. This ensures that the query produces meaningful results by grouping and aggregating the data correctly.

Additionally, you can use other aggregate functions such as COUNT, AVG, MIN, MAX, etc., in combination with the GROUP BY clause to perform various calculations on each group of data.