SQL sum () summation function usage

Source: Internet
Author: User

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;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.