Summation Function in SQL: SUM

The SUM function in the SQL language, despite its simplicity, is used quite often when working with a database. With its help it is convenient to get some intermediate or final results without resorting to the help of auxiliary DBMS tools.

Function Syntax

In most SQL languages, the syntax sum is the same - as an argument, only the field name or some arithmetic action of several of them is used, according to which summation is required.

sql sum

In exceptional cases, it is possible to convey a specific value in the form of a number or a variable, but such "schemes" are practically not used, since they do not carry great value. The following is the syntax of a function in SQL:

sum (a) - here as a parameter a certain numerical value or expression is used

It should be noted that before the parameter you can set keywords, for example, DISTINCT or ALL, which will take only unique or all values, respectively.

SUM example in SQL

For a final understanding of how the function works, consider a few examples. In SQL, SUM can be used both as a return result, and as an intermediate value, for example, to check a condition.

For the first case, consider the option when you want to return the amount of sales for each product, given that the number of purchases made can be in the plural. To get the result, it is enough to execute the following query:

SELECT Commodity, sum (Purchase Sum) FROM Sales GroupBy Commodity;

The answer to this command will be a unique list of goods with a total amount of purchases for each of them.

sql sum examples

For the second example, you need to get a list of goods, the sales amount of which exceeded a certain value, for example, 100. You can get the result for this task in several ways, the most optimal of which is to execute one request:

SELECT Product FROM (SELECT Product, sum (Sum of Purchases) as Total FROM Sales) WHERE Total> 100.

Source: https://habr.com/ru/post/K19593/


All Articles