The total value of an expression returned by the SUM function. This function is also very useful. Let's take a look at the detailed usage of this function.
The syntax of the SUM function is:
The Code is as follows: |
Copy code |
Select sum (expression) FROM tables WHERE predicates; |
The expression can be a numeric field or a formula.
Simple Example
For example, you may want to know that the total salary of all employees is more than USD 25,000/year.
The Code is as follows: |
Copy code |
Select sum (salary) as "Total Salary" FROM employees WHERE salary> 25000; |
Used with Example using DISTINCT
The Code is as follows: |
Copy code |
Select sum (DISTINCT salary) as "Total Salary" FROM employees WHERE salary> 25000; |
Example of using a formula
The expression in the SUM function does not need a single field. You can also use a formula. For example, you may need to calculate the net income of your business. Total income minus total expenditure net income.
The Code is as follows: |
Copy code |
Select sum (income-expenses) as "Net Income" FROM gl_transactions; |
You may also need to perform mathematical operations in the SUM function. For example, you may determine that the total commission is 10% of the total sales.
The Code is as follows: |
Copy code |
Select sum (sales * 0.10) as "Commission" FROM order_details; |
And Example using GROUP
In some cases, you will be asked to use the first group of the SUM function.
For example, you can also use the Department name and total sales (related departments) returned by the SUM function ).
The Code is as follows: |
Copy code |
SELECT department, SUM (sales) as "Total sales" FROM order_details Group by department; |