Posted by : Glen Sajori Sabtu, 27 September 2014

Description

The SQL SUM function is used to return the sum of an expression in a SELECT statement.


Syntax

The syntax for the SQL SUM function is:

SELECT SUM(expression)
FROM tables
WHERE conditions;

Parameters or Arguments

expression can be a numeric field or formula.

Example - With Single Expression

For example, you might wish to know how the combined total salary of all employees whose salary is above $25,000 / year.

SELECT SUM(salary) AS "Total Salary"
FROM employees
WHERE salary > 25000;
 
In this SQL SUM Function example, we've aliased the SUM(salary) expression as "Total Salary". As a result, "Total Salary" will display as the field name when the result set is returned.

Example - Using SQL DISTINCT

You can use the SQL DISTINCT clause within the SQL SUM function. For example, the SQL SELECT statement below returns the combined total salary of unique salary values where the salary is above $25,000 / year.

SELECT SUM(DISTINCT salary) AS "Total Salary"
FROM employees
WHERE salary > 25000;
 
If there were two salaries of $30,000/year, only one of these values would be used in the SQL SUM function.

Example - Using Formula

The expression contained within the SQL SUM function does not need to be a single field. You could also use a formula. For example, you might want the net income for a business. Net Income is calculated as total income less total expenses.
 
SELECT SUM(income - expenses) AS "Net Income"
FROM gl_transactions;
 
You might also want to perform a mathematical operation within the SQL SUM function. For example, you might determine total commission as 10% of total sales.

SELECT SUM(sales * 0.10) AS "Commission"
FROM order_details;

Example - Using SQL GROUP BY

In some cases, you will be required to use the SQL GROUP BY clause with the SQL SUM function.
For example, you could also use the SQL SUM function to return the name of the department and the total sales (in the associated department).

SELECT department, SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department;

Because you have listed one column in your SQL SELECT statement that is not encapsulated in the SQL SUM function, you must use the SQL GROUP BY clause. The department field must, therefore, be listed in the SQL GROUP BY section.

Source : techonthenet.com

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Translate to Your Language

STMIK AMIKOM YOGYAKARTA

Followers

✠Ulquίoґґ∆✠. Diberdayakan oleh Blogger.

Copyright © Free Download+§hare Anything That You Want -Black Rock Shooter- Powered by Blogger - Designed by Johanes Djogan