Concept of SQL GROUP BY Statement

The GROUP BY statement is passed down to group the rows that have the same values in the table.

Grouping allows you to divide data into logical sets so that you can perform a collection of calculations on each group. Groups are built for using the GROUP BY clause in the SELECT statement.

The GROUP BY clause commands the DB2 to group the data and then operate the collection on each group rather than on the entire result set.

The GROUP BY statement is often used with combine functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the conclusion-set by one or more columns.

Syntax

SELECT column_name
FROM table_name
WHERE condition
GROUP BY column_name
ORDER BY column_name;

Table name Customers

Customer IdNameAddressCityPostal codeCountry

001

Ankit New Ashok Nagar H.NO 67/6Lucknow82878India

002

VinayB clash society L810Pune67567India

003

RajuMathur Road near ICIC bank H.no7/290Delhi29867India

004

Karan H.no 456 near kv schoolNoida98689India

005

Sumit Near SPGI hospital house67Goa76687India

Example

SELECT COUNT(CustomerId), City
FROM Customers
GROUP BY City;
SELECT COUNT(CustomerID), City
FROM Customers
GROUP BY City
ORDER BY COUNT(CustomerId) ASC;

GROUP BY With JOIN Example

Table Name Order

Order IdCustomer IdEmployee IdOrder Date    Shipped Id
1029 0086287902020-09-0411900
10220092729892020-07-0412900
10780052828962020-03-0413900
10780042786262020-11-0414900

 

Table Name Shippers

Employee IdShipped IdCompanies Name
00811DTDC Courier company
00677Blue Dart Courier Service
SELECT Shippers.CompaniesName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperId = Shippers.ShipperId
GROUP BY CompaniesName;

 

 

Keywords: