SQL SUM and AVG
The SUM and AVG functions in SQL are used to calculate the sum and average of values in a column, respectively. These functions are often used to find the total or average of a particular type of data, such as the total sales or the average salary in a table.
The syntax for using the SUM and AVG functions
1SELECT SUM(column_name) 2FROM table_name; 3 4SELECT AVG(column_name) 5FROM table_name;
For example, consider a table named sales
with the following columns: id
, date
, product
, quantity
, price
. If you want to find the total sales for all products, you could use the following query:
1SELECT SUM(price * quantity) 2FROM sales;
This query would return the sum of the price * quantity
for each row in the sales
table, which represents the total sales.
If you wanted to find the average price of a product, you could use the following query:
1SELECT AVG(price) 2FROM sales;