What is the usage of “groupby” in MySQL?

In MySQL, GROUP BY is used to group query results based on one or more columns. It is commonly used with aggregate functions (such as COUNT, SUM, AVG, MAX, MIN, etc.) to perform calculations on each group.

The syntax for using GROUP BY is as follows:

SELECT 列1, 列2, ... , 聚合函数
FROM 表名
WHERE 条件
GROUP BY 列1, 列2, ...

Suppose we have a table named orders with columns order_id, customer_id, order_date, and total_amount. We want to group the orders by customer_id and calculate the total amount of orders for each customer.

SELECT customer_id, SUM(total_amount) as total_order_amount
FROM orders
GROUP BY customer_id;

This will return the results grouped by customer_id and calculate the total order amount for each group.

bannerAds