Home > Database > SQL > body text

How to use sum function in sql

下次还敢
Release: 2024-05-02 00:01:01
Original
356 people have browsed it

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>
Copy after login

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>
Copy after login
  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>
Copy after login
  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>
Copy after login
  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>
Copy after login
  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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!