Use of the SQL sum () summation function

Source: Internet
Author: User

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;

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.