Detailed Explanation and Simple Example of SQL GROUP BY

  • 2021-07-01 08:21:51
  • OfStack

The GROUP BY statement is used in conjunction with the Aggregate function to group result sets by one or more columns.

SQL GROUP BY Syntax


SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

Demo database

In this tutorial, we will use the well-known Northwind sample database.

The following data is selected from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID
10248 90 5 1996-07-04 3
10249 81 6 1996-07-05 1
10250 34 4 1996-07-08 2

Data selected from "Shippers" table:

ShipperID ShipperName Phone
1 Speedy Express (503) 555-9831
2 United Package (503) 555-3199
3 Federal Shipping (503) 555-9931

Data selected from "Employees" table:

EmployeeID LastName FirstName BirthDate Photo Notes
1 Davolio Nancy 1968-12-08 EmpID1.pic Education includes a BA....
2 Fuller Andrew 1952-02-19 EmpID2.pic Andrew received his BTS....
3 Leverling Janet 1963-08-30 EmpID3.pic Janet has a BS degree....

Example of SQL GROUP BY

Now we want to find the number of orders delivered by each deliveryman.

The following SQL statement makes order classification statistics by deliveryman:


SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;

GROUP BY more than 1 column

We can also apply the GROUP BY statement to more than one column, as follows:


SELECT Shippers.ShipperName, Employees.LastName,
COUNT(Orders.OrderID) AS NumberOfOrders
FROM ((Orders
INNER JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID)
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY ShipperName,LastName;

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: