In MySQL, adding the values of a column across multiple rows is a common task when analyzing data. This can be accomplished using the SUM() aggregate function.
Consider a table with three columns (A, B, and C):
A | B | C |
---|---|---|
2 | 2 | 2 |
4 | 4 | 4 |
6 | 7 | 8 |
The goal is to calculate the sum of values in each column across all rows in the table. The expected result would be:
A | B | C |
---|---|---|
12 | 13 | 14 |
To sum the values in columns, use the following query:
select sum(A), sum(B), sum(C) from mytable where id in (1, 2, 3);
This query uses the SUM() function to calculate the sum of each column's values. The WHERE clause filters the results to include only rows with IDs 1, 2, and 3, ensuring that the sum is calculated across the desired rows.
The above is the detailed content of How to Sum Column Values in MySQL?. For more information, please follow other related articles on the PHP Chinese website!