This SQLite post explains how to use the SQLite sum function with syntax and examples.
The SQLite sum function returns the summed value of an expression.
The syntax for the sum function in SQLite is:
OR the syntax for the sum function when grouping the results by one or more columns is:
Expressions that are not encapsulated within the sum function and must be included in the GROUP BY clause at the end of the SQL statement.
This is the column or expression that will be summed.
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
Optional. These are conditions that must be met for the records to be selected.
The sum function can be used in the following versions of SQLite:
Let's look at some SQLite sum function examples and explore how to use the sum function in SQLite.
For example, you might wish to know how the combined total salary of all employees whose employee_id is less than 45.
In this sum function example, we've aliased the sum(salary) expression as "Total Salary".
You can use the DISTINCT clause within the sum function. For example, the SQL statement below returns the combined total salary of unique salary values where the salary is above $25,000 / year.
If there were two salaries of $60,000/year, only one of these values would be used in the sum function.
The expression contained within the sum function does not need to be a single field. You could also use a formula. For example, you might want to calculate the total commission.
In some cases, you will be required to use the GROUP BY clause with the sum function.
For example, you could also use the sum function to return the city and the total salaries (in the city) where the state is 'CA'.
Because you have listed one column in your SELECT statement that is not encapsulated in the sum function, you must use a GROUP BY clause. The city field must, therefore, be listed in the GROUP BY section.