Home  >  Article  >  Database  >  How to use sum function in sql

How to use sum function in sql

下次还敢
下次还敢Original
2024-05-02 00:01:01349browse

The SUM() function in SQL is used to calculate the sum of numeric columns. It can calculate sums based on specified columns, filters, aliases, grouping and aggregation of multiple columns, but only handles numeric values ​​and ignores NULL values.

How to use sum function in sql

Usage of SUM() function in SQL

The SUM() function in SQL is used to calculate a set of The sum of the numbers. It is an aggregate function that operates on a set of rows or tables.

Syntax:

<code class="sql">SUM(expression)</code>

Where:

  • expression: The numeric expression or column to be summed.

Usage:

  1. Specify the column to be summed: Specify the specific column to calculate the sum. For example:
<code class="sql">SELECT SUM(salary) FROM employees;</code>
  1. Filter results: Use the WHERE clause to filter data and only count rows that meet specific conditions. For example:
<code class="sql">SELECT SUM(salary) FROM employees WHERE department = 'Sales';</code>
  1. Alias: Specify an alias for the calculation result of the SUM() function for convenience. For example:
<code class="sql">SELECT SUM(salary) AS total_salary FROM employees;</code>
  1. Group: Use the GROUP BY clause to group the data and then calculate the sum for each group. For example:
<code class="sql">SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;</code>
  1. Aggregating multiple columns: SUM() function can calculate the sum of multiple columns at the same time. For example:
<code class="sql">SELECT SUM(salary) + SUM(bonus) AS total_compensation
FROM employees;</code>

Note:

  • The SUM() function is only valid for numeric values.
  • If the column to be calculated contains NULL values, the NULL values ​​will be ignored.
  • The SUM() function can be used with other aggregate functions such as MIN(), MAX(), COUNT().

The above is the detailed content of How to use sum function in sql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn