---
title: "How to get the sum for every distinct value in another column?"  
description: "How to get the sum for every distinct value in another column?"  
author: "Revati S Misra"  
published: 2023-07-27  
updated: 2023-07-28  
canonical: https://www.mindstick.com/forum/159331/how-to-get-the-sum-for-every-distinct-value-in-another-column  
category: "mysql"  
tags: ["database", "mysql", "database table"]  
reading_time: 2 minutes  

---

# How to get the sum for every distinct value in another column?

How to get the [sum](https://www.mindstick.com/forum/159332/how-can-i-use-sum-in-linq) for every [distinct](https://www.mindstick.com/forum/159558/why-c-sharp-linq-distinct-doesn-t-work) [value](https://www.mindstick.com/articles/23219/an-optimized-description-adds-value-to-experience-and-in-turn-effectively-guest-posting-packages) in another [column](https://www.mindstick.com/forum/33860/how-to-calculate-column-summary-in-sql-server)?

## Replies

### Reply by Aryan Kumar

Sure, you can get the sum for every distinct value in another column using the `GROUP BY` clause and the `SUM()` function. The syntax is as follows:

SQL

```plaintext
SELECT distinct_column_name, SUM(column_name)
FROM table_name
GROUP BY distinct_column_name;
```

For example, if you have a table called `products` with the columns `name` and `price`, you could use the following SQL statement to get the sum of all product prices for each unique product name:

SQL

```plaintext
SELECT name, SUM(price)
FROM products
GROUP BY name;
```

This would return a table with two columns: `name` and `sum`. The `name` column would contain the unique product names, and the `sum` column would contain the sum of all product prices for each unique product name.

Here is an example of how to get the sum for every distinct value in another column in MySQL:

SQL

```plaintext
CREATE TABLE products (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  price INT NOT NULL,
  PRIMARY KEY (id)
);

INSERT INTO products (name, price) VALUES
('Product 1', 100),
('Product 2', 200),
('Product 3', 300),
('Product 1', 400),
('Product 2', 500);

SELECT name, SUM(price)
FROM products
GROUP BY name;
```

This will return the following result:

```plaintext
name | sum
------+-----
Product 1 | 500
Product 2 | 700
Product 3 | 300
```

As you can see, the `GROUP BY` clause has grouped the rows in the `products` table by the `name` column. The `SUM()` function has then been used to calculate the sum of all product prices for each unique product name.


---

Original Source: https://www.mindstick.com/forum/159331/how-to-get-the-sum-for-every-distinct-value-in-another-column

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
