In MySQL, The GROUP BY clause is used to group rows based on the values in one or more columns.
It is often used with aggregate functions like SUM, COUNT, AVG, etc., to perform calculations on each group of rows.
SELECT column1, aggregate_function(column2), ... FROM table_name GROUP BY column1, ...;
column1: The column by which we want to group the results.
aggregate_function(column2): An aggregate function applied to another column within each group.
table_name: The name of the table from which we want to retrieve data.
SELECT category, COUNT(*) AS num_products FROM products GROUP BY category;
Note: This query groups the products by the category column and counts the number of products in each category.
SELECT category, AVG(price) AS avg_price, MAX(price) AS max_price FROM products GROUP BY category;
Note: This query groups the products by the category column and calculates the average and maximum price for each category.
SELECT category, price, COUNT(*) AS num_products FROM products GROUP BY category, price;
Note: This query groups the products by both the category and price columns, providing the count of products for each unique combination of category and price.