In SQL, the GROUP BY clause is used to group rows based on one or more columns and apply aggregate functions to each group. It allows you to perform calculations and analysis on subsets of data within a table. The syntax for using GROUP BY is as follows:
sql
SELECT column1, column2, ..., aggregate_function(column)
FROM table
GROUP BY column1, column2, ...;
In this syntax:
- `column1`, `column2`, etc. are the columns you want to group by.
- `aggregate_function(column)` is an aggregate function such as SUM, COUNT, AVG, MAX, MIN, etc., applied to a specific column or expression.
Here are a few examples to illustrate the usage of GROUP BY:
1. Group rows by a single column and calculate the total sales for each category:
sql
SELECT category, SUM(sales) AS total_sales
FROM sales_table
GROUP BY category;
This query groups rows in the `sales_table` by the `category` column and calculates the total sales for each category using the SUM function.
2. Group rows by multiple columns and find the average price for each product in each category:
sql
SELECT category, product, AVG(price) AS average_price
FROM products_table
GROUP BY category, product;
This query groups rows in the `products_table` by the `category` and `product` columns and calculates the average price for each combination of category and product.
3. Group rows by a column and count the number of orders for each customer:
sql
SELECT customer_id, COUNT(order_id) AS order_count
FROM orders_table
GROUP BY customer_id;
This query groups rows in the `orders_table` by the `customer_id` column and counts the number of orders for each customer.
The GROUP BY clause is commonly used with aggregate functions to summarize data and derive meaningful insights from the grouped data. It allows you to perform calculations on specific subsets of data based on the grouping criteria.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc