The syntax for the SUM function is:
The code is as follows |
Copy Code |
SELECT SUM (expression) From tables WHERE predicates; |
An expression can be a numeric field or a formula.
A simple example
For example, you might want to know that the total salary of all employees is more than USD and the salary is 25,000/year
The code is as follows |
Copy Code |
SELECT SUM (Salary) as "total salary" From Employees WHERE salary > 25000; |
In conjunction with the 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 require a single domain. You can also use a formula. For example, you may need net income for the business. Total income minus total net expenditure.
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 on 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; |
With example using GROUP by
In some cases, you will be required to use the SUM function of the first group.
For example, you can also use the unit name and total sales (related department) returned by the SUM function.
code is as follows |
copy code |
SELECT Department, SUM (sales) as "total sales" from Order_Details GROUP by department; |