📜  sql avg 和 group by - SQL (1)

📅  最后修改于: 2023-12-03 15:20:14.189000             🧑  作者: Mango

SQL AVG and GROUP BY

When working with SQL databases, it's often necessary to extract aggregate data from a table. Two common aggregation functions are AVG and GROUP BY. In this article, we'll explore how to use these functions together in SQL.

AVG function

The AVG function is used to calculate the average of a column's values within a table. Its syntax is as follows:

SELECT AVG(column_name)
FROM table_name;

For example, if we have a table called sales with a column price, we can calculate the average price like this:

SELECT AVG(price)
FROM sales;

This will return a single value representing the average price of all the sales in the table.

GROUP BY clause

The GROUP BY clause is used to group rows in a table based on a certain criterion. Its syntax is as follows:

SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name;

For example, if we have a table called sales with columns region and price, we can group the sales by region and calculate the total sales for each region like this:

SELECT region, SUM(price)
FROM sales
GROUP BY region;

This will return a table with two columns - region and SUM(price) - where each row represents a region and its corresponding total sales.

Using AVG and GROUP BY together

Combining the AVG function and GROUP BY clause allows us to calculate the average of a column's values within each group defined by the GROUP BY clause.

For example, if we have the same sales table as before and want to calculate the average price for each region, we can write:

SELECT region, AVG(price)
FROM sales
GROUP BY region;

This will return a table with two columns - region and AVG(price) - where each row represents a region and its corresponding average price.

Conclusion

In this article, we've learned about the AVG function and GROUP BY clause in SQL and how to use them together to extract aggregate data from a table. Understanding these concepts is important for any programmer working with SQL databases.