SQL Aggregate Function SUM()
In SQL, the SUM()
function is an aggregate function that returns the sum of a set of values. The function takes a single argument, which is the name of the column or expression to be evaluated.
Here is an example of using the SUM()
function to find the total sales in a sales
table:
SELECT SUM(sales) AS total_sales FROM sales;
In this example, the SUM()
function is used to find the sum of the sales
column of the sales
table. The AS
keyword is used to alias the column name as total_sales
.
The SUM()
function can also be used with the GROUP BY
clause to find the total value for each group in a table. For example, consider the following sales
table:
+---------+-------+ | product | sales | +---------+-------+ | A | 100 | | A | 200 | | B | 150 | | B | 250 | +---------+-------+
To find the total sales value for each product, we can use the following query:
SELECT product, SUM(sales) AS total_sales FROM sales GROUP BY product;
In this example, the SUM()
function is used with the GROUP BY
clause to find the total sales value for each unique value in the product
column. The result of the query is a table with two columns: product
and total_sales
. The SUM()
function is applied to the sales
column for each group of rows that share the same product
value.