"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sum Columns in MySQL and Return a Single Row?

How to Sum Columns in MySQL and Return a Single Row?

Published on 2024-11-21
Browse:464

How to Sum Columns in MySQL and Return a Single Row?

Summing Elements of Columns in MySQL

In many databases, including MySQL, there are instances where you need to calculate the sum of values in specific columns. To address this, we'll explore how to retrieve a single row showcasing the summed values for each column.

In this scenario, we have a hypothetical table with three columns: A, B, and C. The goal is to select rows from the table and have MySQL return a single row containing the sum of the values in each column.

For instance, consider the following table:

ABC
222
444
678

If we want to sum all three rows, we would expect MySQL to return the following result:

ABC
121314

To achieve this, we can utilize MySQL's SUM() function. Let's construct a query to sum the values for all rows in the table:

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

This query will calculate the sum of values in each column (A, B, and C) for rows where the id column matches the values 1, 2, and 3. The resulting row will contain the summed values, as desired.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3