Calculating Column Sums using MySQL
The requirement is to extract a single row containing the aggregate sum of column values from a table. In this specific case, the table has three columns (A, B, C) and three rows of sample data. The goal is to obtain the total sum for each column when selecting all three rows.
To achieve this in MySQL, utilize the following query:
select sum(A),sum(B),sum(C) from mytable where id in (1,2,3);
Explanation:
This query uses the SUM() function to calculate the aggregate sum of each column. The WHERE() clause specifies the id values for the rows that need to be included in the calculation. In this example, we have specified the IDs as (1,2,3) to include all three rows.
The resulting output will be a single row with the summed values for columns A, B, and C:
A | B | C |
---|---|---|
12 | 13 | 14 |
This query can also be modified to sum a specific range of columns or to filter the table based on additional criteria.
The above is the detailed content of How Can I Calculate Column Sums in MySQL?. For more information, please follow other related articles on the PHP Chinese website!