The GROUP BY clause is used in SQL to group rows with the same values into summary rows. This clause is often used in combination with aggregate functions like SUM, AVG, MIN, MAX, or COUNT, to perform calculations on each group of data. The basic syntax of the GROUP BY clause is as follows:
SELECT column1, aggregate_function(column2), ..., aggregate_function(column_n)
FROM table_name
GROUP BY column1;
In this syntax, column1
represents the column you want to group the data by, and aggregate_function(column2), ..., aggregate_function(column_n)
represent the aggregate functions you want to use to perform calculations on each group of data.
Let’s take a look at a few examples to understand the GROUP BY clause better:
Example 1:
SELECT city, SUM(population)
FROM cities
GROUP BY city;
In this example, the GROUP BY clause groups the data in the cities
table by the city
column, and the SUM function calculates the total population of each city. The result of this query will be a table that displays the city name and the total population of each city.
Example 2:
SELECT department, AVG(salary)
FROM employees
GROUP BY department;
In this example, the GROUP BY clause groups the data in the employees
table by the department
column, and the AVG function calculates the average salary of each department. The result of this query will be a table that displays the department name and the average salary of each department.
Example 3:
SELECT year, MONTH(order_date), SUM(total_sales)
FROM orders
GROUP BY year, MONTH(order_date);
In this example, the GROUP BY clause groups the data in the orders
table by the year and month of the order_date
column, and the SUM function calculates the total sales for each group. The result of this query will be a table that displays the year and month of the order, and the total sales for each group.
In conclusion, the GROUP BY clause is an essential tool for grouping and aggregating data in SQL. It provides a way to organize data into meaningful groups, and to perform calculations on each group of data, making it easier to analyze and understand the data.
Also check WHAT IS GIT ? It’s Easy If You Do It Smart
You can also visite the Git website (https://git-scm.com/)