Home >Database >Mysql Tutorial >How to Calculate the Sum of Column Values in MySQL?

How to Calculate the Sum of Column Values in MySQL?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 21:43:12506browse

How to Calculate the Sum of Column Values in MySQL?

Calculate Column Summation in MySQL

When working with data stored in an SQL database like MySQL, it's often necessary to perform aggregation operations such as calculating the sum of values across rows. Here's a scenario where you need to sum the elements of a column from multiple rows.

Problem:

You have a table with several columns, and you want to select some rows and calculate the total sum for each column. For example, consider the following table:

+---+---+---+
| A | B | C |
+---+---+---+
| 2 | 2 | 2 |
| 4 | 4 | 4 |
| 6 | 7 | 8 |
+---+---+---+

Your goal is to write a MySQL query that will return a single row with the summed values for columns A, B, and C for the selected rows.

Solution:

To achieve this, you can use the SUM() aggregate function along with the WHERE clause to filter the rows. Here's the query:

SELECT SUM(A), SUM(B), SUM(C)
FROM mytable
WHERE id IN (1, 2, 3);

This query calculates the sum of values for columns A, B, and C for rows where the id column matches any of the values in the (1, 2, 3) list. Replace mytable with the actual table name in your database.

In the example scenario, the query would return the following result:

+----+----+----+
| SUM(A) | SUM(B) | SUM(C) |
+----+----+----+
| 12 | 13 | 14 |
+----+----+----+

The above is the detailed content of How to Calculate the Sum of Column Values in MySQL?. 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