MySQL GROUP BY
Introduction to MYSQL GROUP BY clause
The MYSQL GROUP BY Clause is used to collect data from multiple records and group the result by one or more column.
The GROUP BY statement is often used with aggregate functions such as SUM, AVG, MAX, MIN and COUNT. It is generally used in a SELECT statement.
GROUP BY Syntax
SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s) ORDER BY column_name(s);
To understand MySQL GROUP BY clause , consider an “customers” table, which is having the following records −
SELECT * FROM customers;
CustomerID | CustomerName | Age | City | Country |
---|---|---|---|---|
1 | Christina | 40 | London | United Kingdom |
2 | Maria Anders | 56 | Berlin | Germany |
3 | Matthew | 34 | Luleå | Sweden |
4 | Alen | 51 | Berlin | Germany |
5 | Jacob | 28 | México D.F | Mexico |
6 | Aastha | 26 | Chandigarh | India |
7 | Joshua | 21 | México D.F | Mexico |
Now suppose based on the above table you want to count the number of customers in each country, then you can do it as follows −
SELECT COUNT(CustomerID) AS "Number of customers", Country FROM customers GROUP BY Country;
Number of customers | Country |
---|---|
2 | Germany |
1 | India |
2 | Mexico |
1 | Sweden |
1 | United Kingdom |
Below is a selection from the “orders” table, which is having the following records −
SELECT * FROM orders;
OrderID | CustomerID | OrderDate |
---|---|---|
1 | 2 | 2017-02-02 |
2 | 2 | 2017-03-23 |
3 | 4 | 2017-06-14 |
4 | 5 | 2017-06-17 |
5 | 6 | 2017-07-28 |
6 | 6 | 2017-07-31 |
7 | 7 | 2017-09-10 |
8 | 6 | 2017-09-12 |
if you want to count number of orders per customer, then it can be done as follows −
SELECT CustomerName, COUNT(orders.OrderID) AS TotalOrder FROM customers INNER JOIN Orders ON customers.CustomerID = orders.CustomerID GROUP BY customers.CustomerID ORDER BY TotalOrder DESC;
CustomerName | TotalOrder |
---|---|
Aastha | 3 |
Maria Anders | 2 |
Joshua | 1 |
Alen | 1 |
Jacob | 1 |