Home  >  Article  >  Database  >  How to Sum Columns in MySQL and Return a Single Row?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-21 08:32:10399browse

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:

A B C
2 2 2
4 4 4
6 7 8

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

A B C
12 13 14

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.

The above is the detailed content of How to Sum Columns in MySQL and Return a Single Row?. 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